MVC中数据的内部校验
针对MVC中实例类型的修饰,我们可以采用DataAnnotations类来完成,该类所处的命名空间是System.ComponentModel.DataAnnotations;
一、通过开类型,能够修改Model类型的属性,如下代码所示:
public class Employee { [Key] public int EmployeeId { get; set; } [Required(ErrorMessage = "Enter First Name"), StringLength(50)] public string FirstName { get; set; } [StringLength(50,ErrorMessage="Last Name length should be greater than 50")] public string LastName { get; set; } public int Salary { get; set; } }
备注:
1、[key]主键唯一,Required必填,ErrorMessage错误提示内容,StringLength表述字段长度。
Form表单代码:
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>CreateEmployee</title> </head> <body> <div> <form action="/Employee/SaveEmployee" method="post"> <table> <tr> <td>First Name:</td> <td><input type="text" id="TxtFName" name="FirstName" value="" /></td> <td>@Html.ValidationMessage("FirstName")</td> </tr> <tr> <td>Last Name:</td> <td><input type="text" id="TxtLName" name="LastName" value="" /></td> <td>@Html.ValidationMessage("LastName")</td> </tr> <tr> <td>Salary:</td> <td><input type="text" id="TxtSalary" name="Salary" value="" /></td> <td>@Html.ValidationMessage("Salary")</td> </tr> <tr> <td> <input type="submit" name="BtnSave" value="Save Employee" /> <input type="submit" name="BtnSave" value="Cancel" /> </td> </tr> </table> </form> </div> </body> </html>
备注:@Html.ValidationMessage表述验收字段异常时,显示异常提示信息。
后台Action代码:
public ActionResult SaveEmployee(Employee et, string BtnSave) { switch (BtnSave) { case "Save Employee": if (ModelState.IsValid) { EmployeeBusinessLayer empbal = new EmployeeBusinessLayer(); empbal.SaveEmployee(et); return RedirectToAction("Index"); } else { return View("CreateEmployee"); } case "Cancel": // RedirectToAction("index"); return RedirectToAction("Index"); } return new EmptyResult(); }
备注:ModelState.IsValid表述Model字段验证是否有效
二、自定义服务端验证
1、新建自定义类:
public class FirstNameValidation : ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (value == null) { return new ValidationResult("Please Provide First Name"); } else { if (value.ToString().Contains("@")) { return new ValidationResult("First Name should not contain @"); } } return ValidationResult.Success; } }
2、使用自定义验证类型
public class Employee { [Key] public int EmployeeId { get; set; } [Required(ErrorMessage = "Enter First Name"), StringLength(50), FirstNameValidation] public string FirstName { get; set; } public int Salary { get; set; } }