我在 ASP.NET MVC3 模型中有一个员工类。有一个名为“EmpName”的字段。有一个用于创建员工记录的创建操作。应该有一个服务器端验证——名字的第二个字母应该是“E”,名字的第三个字母应该是“F”。 (没有客户端验证)。如果验证失败,该消息应作为验证摘要显示在创建 View 中。我们如何做到这一点?
注意:这两个验证的验证错误预计会作为两个错误结果(两个不同的行)出现。
注意:我没有使用 Entity Framework
查看代码如下。
@model MyApp.Employee
@{ ViewBag.Title = "Create"; }
<h2>Create</h2>
@using (Html.BeginForm())
{
<div > EmpName :~: @Html.EditorFor(model => model.EmpName) </div>
Controller
// 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");
}
}
阅读:
http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html
Add Sorting and Searching in Contact Management ASP.NET MVC Application
ValidationSummary and ValidationMessageFor with custom CSS shown when no errors present
http://www.devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc-3-part-1
What is the better ASP.NET MVC 3.0 Custom Validation approach
http://dotnetslackers.com/articles/aspnet/Validating-Data-in-ASP-NET-MVC-Applications.aspx
请您参考如下方法:
您的模型可以实现 IValidatableObject(在 System.ComponentModel.DataAnnotations 命名空间 内)
您的模型应该如下所示:
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 方法中进行验证。
现在在 Controller 上,如果您在无效对象上调用 ModelState.IsValid,则会失败并返回两个错误并将它们都显示给用户。
