標籤:
Model驗證是ASP.NET MVC中的重要部分,這篇文章就介紹下ASP.NET MVC中Model驗證的幾種方式。
- DataAnnotation
- ValidationAttribute
- IValidatableObject
- IDataErrorInfo
DataAnnotation
DataAnnotation翻譯過來是“資料註解”的意思,DataAnnotation命名空間中包含一些用於驗證Model的特性,如:RequiredAttribute,CompareAttribute,DisplayAttribute等,我們在建立Model時,將相應的特性性標註到欄位上即可實現資料驗證。
建立Model:
public class Person{ [Display(Name = "姓名")] [Required(ErrorMessage = "姓名是必須的!")] public string Name { set; get; } [Display(Name = "姓名")] public int Age { set; get; }}
View中的代碼:
@model EBuy.Website.Models.Person@{ Layout = null;}<!DOCTYPE html><html><head> <meta name="viewport" content="width=device-width" /> <title>Index</title></head><body> <div> <h3 style="color:red;"> @Html.ValidationSummary() </h3> </div> <div> @using (Html.BeginForm("evaluate", "home", "Post")) { @Html.LabelFor(Model => Model.Name) @Html.TextBoxFor(Model => Model.Name) @Html.LabelFor(Model => Model.Age) @Html.TextBoxFor(Model => Model.Age) <input type="submit" value="提交" /> } </div></body></html>
Controller中的代碼:
public class HomeController : Controller{ public ActionResult Index() { return View(); } public ActionResult Evaluate(Person person) { if (ModelState.IsValid) { return Content("evaluate success!"); } return View("Index", person); }}
運行程式:
注意,Age屬性上並未標註RequiredAttribute,卻依然提示Age欄位必須,這是因為Age是int類型,int類型不能為null,對於不能為null的類型,ASP.NET MVC預設為是必須的。
ValuationAttribute
除了使用DataAnnotation中預定義的一些特性進行資料驗證外,我們還可以自訂一些驗證特性。這裡我們通過覆寫DataAnnotation命名空間中ValudationAttribute類的IsValid方法來實現自訂驗證。範例程式碼如下:
public class CheckAgeAttribute : ValidationAttribute{ private int _minage; public CheckAgeAttribute(int minAge) { _minage = minAge; } public override bool IsValid(object value) { if (value is int) { var age = value as int?; if (age == null) { return false; } if (age < _minage) { return false; } return true; } return false; } public override string FormatErrorMessage(string name) { return base.FormatErrorMessage(name); }}
標註特性:
public class Person{ [Display(Name = "姓名")] [Required(ErrorMessage = "姓名是必須的!")] [MaxLength(4, ErrorMessage = "太長了")] public string Name { set; get; } [Display(Name = "年齡")] [CheckAge(18, ErrorMessage = "年紀太小!")] public int Age { set; get; }}
然後運行程式:
IValidatableObject
通過實現IValidatableObject介面進行資料的驗證,範例程式碼如下:
public class Person : IValidatableObject{ [Display(Name = "姓名")] public string Name { set; get; } [Display(Name = "年齡")] public int Age { set; get; } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { Person person = validationContext.ObjectInstance as Person; if (person == null) { yield break; } if (string.IsNullOrEmpty(person.Name)) { yield return new ValidationResult("您貴姓?"); } if (person.Age < 18) { yield return new ValidationResult("太年輕了!"); } }}
運行程式:
IDataErrorInfo
實現IDataErrorInfo介面也可以進行資料的驗證,範例程式碼如下:
public class Person : IDataErrorInfo{ [Display(Name = "姓名")] public string Name { set; get; } [Display(Name = "年齡")] public int Age { set; get; } public string this[string columnName] { get { switch (columnName) { case "Name": if (string.IsNullOrEmpty(Name)) { return "雁過留聲,人過留名"; } return null; case "Age": if (Age < 18) { return "年紀尚輕!"; } break; } return null; } } public string Error { get { return "出錯啦!"; } }}
運行程式:
著作權聲明
本文為作者原創,著作權歸作者雪飛鴻所有。 轉載必須保留文章的完整性,且在頁面明顯位置處標明原文連結。
如有問題, 請發送郵件和作者聯絡。
ASP.NET MVC5中的Model驗證