2017年2月28日-----------亂碼新手自學.net 之特性與驗證

來源:互聯網
上載者:User

標籤:狀態   對象   blog   inf   使用   摘要   require   控制   erro   

現在看asp.net MVC5自學已經到了第六章:資料註解與驗證。

話得從以前看MVC music store(音樂市集項目)的源碼說起,

最初看music store源碼完全就是一臉懵逼,整個程式,找了半天,只看到控制器有少許邏輯代碼,例如編輯專輯的視圖裡面,使用者輸入的title到底符不符合規範, VIEW裡面即無相關驗證的JS代碼,又沒有進行背景資料判斷。

 1 @using (Html.BeginForm()) { 2     @Html.ValidationSummary(true) 3     <fieldset> 4         <legend>Album</legend> 5  6         @Html.HiddenFor(model => model.AlbumId) 7  8         <div class="editor-label"> 9             @Html.LabelFor(model => model.GenreId, "Genre")10         </div>11         <div class="editor-field">12             @Html.DropDownList("GenreId", String.Empty)13             @Html.ValidationMessageFor(model => model.GenreId)14         </div>15 16         <div class="editor-label">17             @Html.LabelFor(model => model.ArtistId, "Artist")18         </div>19         <div class="editor-field">20             @Html.DropDownList("ArtistId", String.Empty)21             @Html.ValidationMessageFor(model => model.ArtistId)22         </div>23 24         <div class="editor-label">25             @Html.LabelFor(model => model.Title)26         </div>27         <div class="editor-field">28             @Html.EditorFor(model => model.Title)29             @Html.ValidationMessageFor(model => model.Title)30         </div>31 32         <div class="editor-label">33             @Html.LabelFor(model => model.Price)34         </div>35         <div class="editor-field">36             @Html.EditorFor(model => model.Price)37             @Html.ValidationMessageFor(model => model.Price)38         </div>39 40         <div class="editor-label">41             @Html.LabelFor(model => model.AlbumArtUrl)42         </div>43         <div class="editor-field">44             @Html.EditorFor(model => model.AlbumArtUrl)45             @Html.ValidationMessageFor(model => model.AlbumArtUrl)46         </div>47 48         <p>49             <input type="submit" value="Save" />50         </p>51     </fieldset>52 }
音樂市集編輯專輯的視圖

 

程式到底是怎麼完成資料驗證呢?

今天看了這一章對資料驗證就有了大概的瞭解了。

===========================================================

前提:C# Attribute特性和反射

  翻到專輯的Model(實體類)裡,我們看到Album類的定義是這樣的。

public class Album    {        [ScaffoldColumn(false)]        public int AlbumId { get; set; }        [DisplayName("Genre")]        public int GenreId { get; set; }        [DisplayName("Artist")]        public int ArtistId { get; set; }        [Required(ErrorMessage = "An Album Title is required")]        [StringLength(160)]        public string Title { get; set; }        [Required(ErrorMessage = "Price is required")]        [Range(0.01, 100.00,            ErrorMessage = "Price must be between 0.01 and 100.00")]        public decimal Price { get; set; }        [DisplayName("Album Art URL")]        [StringLength(1024)]        public string AlbumArtUrl { get; set; }        public virtual Genre Genre { get; set; }        public virtual Artist Artist { get; set; }        public virtual List<OrderDetail> OrderDetails { get; set; }

  原來,模型類裡面大量採用attribute特性

  關於Attribute特性我原先一直沒有搞懂它到底是怎麼運作的。寫個方括弧,括起來一個類,為什麼就能讓我的屬性、方法、類有了限制?

  下面我首先簡介一下Attribute特性的一些基本要點:

    1、屬性類別其實就是一個從Attribute基類繼承而來的類。

    2、自訂Attribute只能在反射時生效。

  等等,第二個基本要點中:反射。它的定義就是反射指程式可以訪問、檢測和修改它本身狀態或行為的一種能力。

  這也就是說,利用反射,我們可以得到一個類裡面所有的特性。似乎我可以猜測到一點特性的運行原理了:我們可以在屬性類別中做文章,在反射時,擷取了被標註的類的所有特性,運行這個這些特性的某些方法或者屬性,就可以對這個被標註的類進行驗證或者限制。

  

驗證的運行原理:利用特性來進行驗證。

  

 [StringLength(160)]        public string Title { get; set; }

  在上面一個屬性中,有一個StringLengt(160)的特性,MVC書上稱他為驗證。

  // 摘要:     //     指定資料欄位中允許的最小和最大字元長度。    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]    public class StringLengthAttribute : ValidationAttribute    {        // 摘要:         //     使用指定的最大長度初始化 System.ComponentModel.DataAnnotations.StringLengthAttribute        //     類的新執行個體。        //        // 參數:         //   maximumLength:        //     字串的最大長度。        public StringLengthAttribute(int maximumLength);        // 摘要:         //     擷取或設定字串的最大長度。        //        // 返回結果:         //     字串的最大長度。        public int MaximumLength { get; }        //        // 摘要:         //     擷取或設定字串的最小長度。        //        // 返回結果:         //     字串的最小長度。        public int MinimumLength { get; set; }        // 摘要:         //     對指定的錯誤訊息應用格式設定。        //        // 參數:         //   name:        //     要進行格式設定的錯誤訊息。        //        // 返回結果:         //     帶有格式的錯誤訊息。        //        // 異常:         //   System.ArgumentOutOfRangeException:        //     maximumLength 為負數。- 或 -maximumLength 小於 minimumLength。        public override string FormatErrorMessage(string name);        //        // 摘要:         //     確定指定的對象是否有效。        //        // 參數:         //   value:        //     要驗證的對象。        //        // 返回結果:         //     如果指定的對象有效,則為 true;否則為 false。        //        // 異常:         //   System.ArgumentOutOfRangeException:        //     maximumLength 為負數。- 或 -maximumLength 小於 System.ComponentModel.DataAnnotations.StringLengthAttribute.MinimumLength。        public override bool IsValid(object value);    }

  翻開它的中繼資料我們可以看到,它其實就是一個微軟提供的自訂特性。它繼承自ValidationAttribute,ValidationAttribute又繼承自Attribute

  通過中繼資料我們可以看到,它其中有一個重寫的bool IsVlid(object value) 方法,它就是用來判斷被標註的對象是否驗證成功的入口。

  實際上,翻開ValidationAttribute的中繼資料,IsValid方法提供了很多重載版,驗證特性要成功,最少都要重寫一個方法,在方法裡進行邏輯判斷,確定是否驗證成功。

==========================================================================================

MVC特性驗證的原理

  以下是書上的解釋:

  1、asp.net mvc架構可以自動綁定模型,如果控制器帶了參數,MVC運行時會隱式地根據參數類型的標識符,從GET或者POST來的索引值對裡面找相同名字的鍵填儲值。當然,控制器不帶參數,也可以通過tryupdatemodel,或者updatemodel兩個方法來完成模型繫結。

  2、在模型繫結之後,下一步就是反射被綁定後的模型,反射擷取這個模型對象的驗證特性,也就是例如[StringLength(160)]這些特性。

  3、得到所有驗證特性之後,就調用這些驗證屬性類別的isvalid方法,對被綁定屬性進行驗證。

  4、MVC運行時會捕捉所有isvalid方法傳回值為false的驗證規則,並把他們加入到ModelState中。

  5、如果ModelState中有任何一個驗證的失敗資訊,ModelState的isValid屬性都將設定為False。

  6、在前端視圖中,我們就可以調用一個輔助方法: @Html.ValidationMessageFor(model => model.GenreId),去ModelState中找這個錯誤,輔助方法會自動根據ModelState中的錯誤資訊拼裝包含你傳入的資料拋出的驗證錯誤的HTML。

  如此一來,通過這6個步驟,僅僅依靠特性就能對資料進行驗證。大大地提高了編碼效率,減少了編碼量

 

 

2017年2月28日-----------亂碼新手自學.net 之特性與驗證

聯繫我們

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