ASP.NET MVC5中的Model驗證

來源:互聯網
上載者:User

標籤:

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驗證

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.