我有部分视图通过ajax调用添加到主视图,由用户单击按钮触发(用户单击按钮,部分视图添加到页面中)。
部分视图强烈类型化为与主页面不同的模型。在我的主页面中,我在顶部显示验证错误,然后在每个字段下方显示消息。部分视图的验证错误显示在页面顶部,但它们不会显示字段本身。
部分视野中的字段:
<td>
@Html.LabelFor(model => model.EmploymentCompany, "* Employer Name")
<input type="text" name="TempEmployments[@idx].EmploymentCompany" class="field panel-field" maxlength="40" style="width: 250px !important;" value="@EmploymentCompany"/>
@Html.ValidationMessage("EmploymentCompany")
</td>
呈现为:
<td>
<label for="EmploymentCompany">* Employer Name</label>
<input type="text" name="TempEmployments[0].EmploymentCompany" class="field panel-field" maxlength="40" style="width: 250px !important;">
<span class="field-validation-valid" data-valmsg-for="EmploymentCompany" data-valmsg-replace="true"></span>
<td>
在控制器中,调用验证:
[HttpPost]
public ActionResult Create(Applicant application)
{
this.ModelState.AddModelErrors(application.Validate(update: false));
//if valid, other stuff is done. otherwise:
return View(application);
}
在主视图中,验证错误显示在顶部:
if (!this.ViewData.ModelState.IsValid)
{
<div class="validation-summary-errors" data-valmsg-summary="true">
<ul>
@foreach (ModelState modelState in ViewData.ModelState.Values)
{
foreach (ModelError error in modelState.Errors)
{
<li>@Html.Raw(error.ErrorMessage)</li>
}
}
</ul>
</div>
}
在添加验证错误的实体中:
foreach (var job in TempEmployments)
{
if (string.IsNullOrWhiteSpace(job.EmploymentCompany))
{
errorDictionary.Add("EmploymentCompany", "Company Name is required");
}
}
以下是页面顶部的错误:
部分观点: