在 Web 表单中使用视图状态。但是在 ASP.NET MVC 中,由于模型绑定可用,因此可以在控制器中轻松访问属性。但是,当模型验证失败时,ASP.NET MVC 是否会自动填充表单控件以实现验证失败?
或者有没有其他方法可以做到这一点。
在 Web 表单中使用视图状态。但是在 ASP.NET MVC 中,由于模型绑定可用,因此可以在控制器中轻松访问属性。但是,当模型验证失败时,ASP.NET MVC 是否会自动填充表单控件以实现验证失败?
或者有没有其他方法可以做到这一点。
有一个名为ModelState
(在Controller
类中)的属性,它包含所有值。它用于模型绑定。当验证失败时,ModelState
保存所有有验证错误的值。
ModelState.IsValid
告诉你,验证没有抛出任何错误。
ModelState.Values
保存所有值和错误。
编辑
Ufuk 的示例:
查看型号:
public class EmployeeVM
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
行动:
[HttpGet]
public ActionResult CreateEmployee()
{
return View();
}
[HttpPost]
public ActionResult CreateEmployee(EmployeeVM model)
{
model.FirstName = "AAAAAA";
model.LastName = "BBBBBB";
return View(model);
}
看法:
@model MvcApplication1.Models.EmployeeVM
@using (Html.BeginForm("CreateEmployee", "Home")) {
@Html.EditorFor(m => m)
<input type="submit" value="Save"/>
}
如您所见,在 POST 方法中,值被 AAAAA 和 BBBBB 覆盖,但在 POST 之后,表单仍然显示发布的值。它们取自ModelState
.