[英]ASP.NET MVC3: Validation Summary for Create Action (Server Side Validation)
我在ASP.NET MVC3模型中有一个员工类。 有一个名为“ EmpName”的字段。 有一个用于创建员工记录的创建动作。 应该在服务器端进行验证-名称的第二个字母应为“ E”,名称的第三个字母应为“ F”。 (没有客户端验证)。 如果验证失败,则该消息应作为验证摘要显示在创建视图中。 我们如何做到这一点?
注意:这两个验证的验证错误预计将作为两个错误结果(两个不同的行)出现。
注意:我没有使用实体框架
以下是查看代码。
@model MyApp.Employee
@{ ViewBag.Title = "Create"; }
<h2>Create</h2>
@using (Html.BeginForm())
{
<div > EmpName :~: @Html.EditorFor(model => model.EmpName) </div>
控制器
// GET:
public ActionResult Create()
{
return View();
}
// POST:
[HttpPost]
public ActionResult Create(Employee emp)
{
if (ModelState.IsValid)
{
//Save the employee in DB first and then redirectToAction.
return RedirectToAction("Index");
}
}
读:
您可以使用ModelState.AddModelError添加服务器端错误。 当ModelState
包含错误时,将导致ModelState.IsValid
为false。
[HttpPost]
public ActionResult Create(Employee emp)
{
if (YourServerValidation(emp) == false)
{
ModelState.AddModelError("EmpName", "Invalid value");
}
if (ModelState.IsValid)
{
//Save the employee in DB first and then redirectToAction.
return RedirectToAction("Index");
}
else
{
return View(emp);
}
您的视图应更新如下:
<div>
EmpName :~: @Html.TextBoxFor(model => model.EmpName)
@Html.ValidationMessageFor(model => model.EmpName)
</div>
您的模型可以实现IValidatableObject
(在System.ComponentModel.DataAnnotations namespace
内部)
您的模型应如下所示:
public class Employee : IValidatableObject
{
public string EmployeeName;
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
char secondNameChar = EmployeeName[1];
char thirdNameChar = EmployeeName[2];
if (secondNameChar.ToString().ToLower() != "e")
yield return
new ValidationResult("Second char of name should be 'E'",
new[] {"EmployeeName"});
if (thirdNameChar.ToString().ToLower() != "f")
yield return
new ValidationResult("Third char of name should be 'F'",
new[] {"EmployeeName"});
}
}
请注意,将雇员的其他属性添加到此类中,然后在Validate
方法中进行Validate
。
现在在控制器上,如果您在无效对象上调用ModelState.IsValid
,则此操作将失败并返回两个错误,并向用户显示它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.