首页 > 解决方案 > 为什么即使字段与表单一起传递,我也会收到“字段是必需的”验证错误?

问题描述

我正在编写一个 .NET Core 3.0 MVC Web 应用程序。我有一个JobApplication看起来像这样的模型:

    public class JobApplication
    {
        [Key]
        public int Id{ get; set; }
        [Required]
        public DateTime CreatedOn { get; set; }

        [DataType(DataType.Date)]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyy-MM-dd}")]
        [Display(Name = "Edited on:")]
        public DateTime? EditedOn { get; set; }
        [DataType(DataType.Date)]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyy-MM-dd}")]
        [Display(Name = "Deleted on:")]
        public DateTime? DeletedOn { get; set; }

        [Required]
        public User Applicant { get; set; }
        [Required]
        public JobOffer JobOffer { get; set; }
        [Required]
        public ApplicationStatus ApplicationStatus { get; set; }

        public string CvHandle { get; set; }
        public string AdditionalInformation { get; set; }
    }

如您所见,该模型包含对其创建的工作机会和创建应用程序的申请人的引用。

我也有一个控制器JobApplicationController,它有 2Create种方法:

        public async Task<ActionResult> Create(int? id)
        {
            var offer = await _context.JobOffers.Include(x => x.CreatedFor).FirstOrDefaultAsync(x => x.Id == id.Value);
            var user = await _context.Users.FirstOrDefaultAsync(x => x.Name == "Filip");

            var model = new JobApplication()
            {
                JobOffer = offer,
                Applicant = user
            };
            return View(model);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Create([FromForm]JobApplication model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            JobApplication ja = new JobApplication
            {
             ...
            };

            await _context.JobApplications.AddAsync(ja);
            await _context.SaveChangesAsync();
            return RedirectToAction("Index");
        }

如您所见,其中一个返回Create视图,另一个从视图中获取模型并将其添加到数据库中。我还强调,在第一种方法中,“JobOffer”和“Applicant”字段是从数据库中获取的,并通过模型传递给表单。以下是视图的设置方式:

@model HRpest.BL.Model.JobApplication

@{
    ViewData["Title"] = "Create";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Create">
            @Html.Hidden("Offer", Model.JobOffer)
            @Html.Hidden("Applicant", Model.Applicant)
            <div asp-validation-summary="None" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="CvHandle" class="control-label"></label>
                <input asp-for="CvHandle" class="form-control" />
                <span asp-validation-for="CvHandle" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="AdditionalInformation" class="control-label"></label>
                <input asp-for="AdditionalInformation" class="form-control" />
                <span asp-validation-for="AdditionalInformation" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

一切似乎都很好。但是,当我尝试添加应用程序并提交表单时,出现错误:

{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId":"|a72c03fc-4f6501d7781e4a9a.","errors":{"JobOffer":["The JobOffer field is required."],"Applicant":["The Applicant field is required."]}}

我不明白。我的模型中有两个字段。如何让它消失?

非常感谢你。

标签: c#asp.netasp.net-mvcrazor

解决方案


您需要使用 HiddenFor() 而不是 Hidden()。

阅读此处以了解两者之间的区别。


推荐阅读