ASP.NET MVC3中Model驗證

來源:互聯網
上載者:User

標籤:style   blog   http   java   color   使用   

原文: ASP.NET MVC3中Model驗證

 概述

上節我們學習了Model的資料在介面之間的傳遞,但是很多時候,我們在資料傳遞的時候為了確保資料的有效性,不得不給Model的相關屬性做基本的資料驗證。

本節我們就學習如何使用 System.ComponentModel.DataAnnotations 命名空間中的特性指定對資料模型中的各個欄位的驗證。

這些特性用於定義常見的驗證模式,例如範圍檢查和必要欄位。而 DataAnnotations 特性使 MVC 能夠提供用戶端和伺服器驗證檢查,使你無需進行額外的編碼來控制資料的有效。

System.ComponentModel.DataAnnotations 特性可用於實體資料模型 (EDM)、LINQ to SQL 和其他資料模型。 還可以建立自訂驗證特性。

關於DataAnnotations請看System.ComponentModel.DataAnnotations概述

資料層級的驗證

建立項目建立名為User的Model類

public class User{    public int ID { get; set; }}

以Create驗證為例來學習DataAnnotations 驗證。

建立Create方法

//建立        // GET: /User/Create        public ActionResult Create()        {    return View();        } 

添加視圖

注意:在添加視圖的時候,如果強型別視圖找不到Model,建議在重建解決方案。

非空驗證

public class User{    public int ID { get; set; }    [DisplayName("姓名")]    [Required(ErrorMessage = "姓名不可為空")]    public string Name { get; set; }}

添加視圖直接運行

字元長度驗證

public class User{    public int ID { get; set; }    [DisplayName("姓名")]    [Required(ErrorMessage = "姓名不可為空")]    public string Name { get; set; }    [DisplayName("密碼")]    [StringLength(6, ErrorMessage = "密碼不能超過6個字元")]    public string Password { get; set; }}

添加視圖後直接運行

數字驗證

 [DisplayName("年齡")] [Range(1, int.MaxValue, ErrorMessage = "請輸入大於等於1的數")]         public int Age { get; set; }

添加視圖直接運行

Regex驗證

[DisplayName("電子郵件")]       [RegularExpression(@"^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$",  ErrorMessage = "請輸入正確的Email格式\n樣本:[email protected]")]        public string Email { get; set; }

添加視圖後運行效果

商務邏輯驗證

遠程服務端驗證

Remote非同步請求驗證,在[HttpGet]時擷取指定Controller裡面的指定方法驗證,此方法必須是[HttpGet]標記的,傳回型別為Json類型的JavaScript對象。

Model代碼

[DisplayName("姓名")]        [Required(ErrorMessage = "姓名不可為空")]       [Remote("GetUser", "User", ErrorMessage = "該姓名已存在")]       public string Name { get; set; }

Controller代碼

//HttpGet是必須加的[HttpGet]        public ActionResult GetUser(string name)        {    return Json(name != "aa", JsonRequestBehavior.AllowGet);        }

直接添加視圖運行

自訂Attbitue驗證

Model代碼

[Required][StringLength(15)][LoginUnique]public string Login { get; set; }

Attribute代碼

    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]    public sealed class LoginUniqueAttribute : ValidationAttribute    {        private static readonly string DefaultErrorMessage = "login unique";//MUI.login_unique;        public LoginUniqueAttribute()            : base(DefaultErrorMessage)        {        }        public override string FormatErrorMessage(string name)        {            return DefaultErrorMessage;        }        public override bool IsValid(object value)        {             return UserService.Check(p=>p.Name==value.ToString());        }    }

直接添加視圖運行

總結

其實微軟DataAnnotations驗證一直是在VS平台上面充分運用的,不管是Web程式還是WForm程式甚至是Silverlight程式,都可以使用微軟提高的DataAnnotations驗證,可以說是無孔不入啊。不過就這三種程式而言,MVC的驗證相對來說還是比較完善的,簡單適用。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.