验证消息不是通过模板的编辑器显示的形式
本文关键字:编辑器 显示 消息 验证 | 更新日期: 2023-09-27 18:19:41
我正在创建一个简单的MVC3应用程序,在该应用程序中,我使用editorfor模板来显示一个包含两个字段的简单表单,并且这些属性具有具有"Required"属性的模型级验证。但是,当我点击表单上的提交按钮并检查控制器操作中的ModelState时,它显示为Invalid,但错误消息没有显示在表单中。
我正在粘贴下面的代码:
1) 型号:
public class EmployeeList
{
public List<Employee> ListOfEmployees { get; set; }
}
public class Employee
{
[Required(ErrorMessage="{0} is required.")]
public int? Id { get; set; }
[Required(ErrorMessage="{0} is required.")]
public string Name { get; set; }
}
2) 控制器动作:
[HttpPost]
public ActionResult AddEmployee(EmployeeList ListOfEmployees1)
{
if (ModelState.IsValid)
{
service.AddEmployee(ListOfEmployees1);
return RedirectToAction("ListofEmployees");
}
return View();
}
3) 主视图(AddEmployee.cshtml):
@using (Html.BeginForm("AddEmployee", "Home", FormMethod.Post, new { @id = "testForm" }))
{
@Html.EditorFor(x => x.ListOfEmployees)
<p>
<input type="submit" value="Add" />
</p>
}
模板视图编辑器(Employee.cshtml):
@model test.Models.Employee
<table border="0">
<tr>
<td>@Html.LabelFor(model => model.Id)</td>
<td>@Html.TextBoxFor(model => model.Id)
@Html.ValidationMessageFor(model => model.Id)
</td>
</tr>
<tr>
<td>@Html.LabelFor(model => model.Name)</td>
<td>@Html.TextBoxFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</td>
</tr>
</table>
如果我使用部分视图而不是editor-for-template来显示这两个字段,则表单上会出现验证消息,但editor-for template不会出现同样的情况。有人能帮忙吗?
在您的操作方法中,返回带有模型的视图
[HttpPost]
public ActionResult AddEmployee(EmployeeList ListOfEmployees1)
{
if (ModelState.IsValid)
{
....
}
return View(ListOfEmployees1);
}
我怀疑它不起作用,因为您对集合类型的模型使用EditorFor。相反,可以尝试以下方法:
@for(var i=0; i< Model.ListOfEmployees.Count; i++){
Html.EditorFor(m => m.ListOfEmployees[i])
}