日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關咨詢
選擇下列產(chǎn)品馬上在線溝通
服務時間:8:30-17:00
你可能遇到了下面的問題
關閉右側工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
使用VisualStudio2010和MVC2.0增強驗證功能

在開始之前,我不得不說明我已經(jīng)安裝了Visual Studio 2010 RC1,并使用它將老版本轉換為ASP.Net 4.0,大多數(shù)情況下,當你接收到來自用戶從form表單post來的信息后,你的驗證代碼往往會檢查相應的值是否存在,數(shù)據(jù)類型是否正確以及數(shù)據(jù)的范圍是否正確。

創(chuàng)新互聯(lián)公司:成立于2013年為各行業(yè)開拓出企業(yè)自己的“網(wǎng)站建設”服務,為1000多家公司企業(yè)提供了專業(yè)的成都網(wǎng)站設計、成都網(wǎng)站建設、網(wǎng)頁設計和網(wǎng)站推廣服務, 按需定制由設計師親自精心設計,設計的效果完全按照客戶的要求,并適當?shù)奶岢龊侠淼慕ㄗh,擁有的視覺效果,策劃師分析客戶的同行競爭對手,根據(jù)客戶的實際情況給出合理的網(wǎng)站構架,制作客戶同行業(yè)具有領先地位的。

如果將驗證代碼放到一個集中的地方時,那類似上面所說的改變會不會變得更簡單些?Model中的DataAnnotations正是為此而來,在MVC 2.0中,這一特性被包含在內。

DataAnnotations作為.net Framework的一部分已經(jīng)有一段時間了,但是MVC 2.0中增加了ModelMetaData類,這是儲存MetaData的容器,默認會使用同樣也是新增類的DataAnnotationsMetaDataProvider類。因為傳入的值會由Action方法接受model binding作為匹配傳入?yún)?shù)和action的參數(shù)而介入。

在MVC 2.0中,默認的model binder使用DataAnnotationsMetaDataProvider來獲取metadata中model binder嘗試匹配的對象,如果驗證用的metadata存在,則其會通過對對象的屬性和傳入的值比較來進驗證,這類meta由你通過使用標簽(Attribute)修飾屬性來實現(xiàn)。

下面例子中我通過原程序中添加聯(lián)系人這一過程來描述使用DataAnnotatioins的方法,這里我們使用自定義ViewModel,名為:ContactPersonViewModel。通過Contact.Add()這個action方法來添加聯(lián)系人,代碼如下:

 
 
 
 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Web.Mvc;  
  4. using System.ComponentModel;  
  5.  
  6. namespace ContactManagerMVC.Views.ViewModels  
  7. {  
  8.   public class ContactPersonViewModel  
  9.   {  
  10.     public int Id { get; set; }  
  11.     public string FirstName { get; set; }  
  12.     public string MiddleName { get; set; }  
  13.     public string LastName { get; set; }  
  14.     public DateTime DateOfBirth { get; set; }  
  15.     public IEnumerable Type { get; set; }  
  16.   }  
  17. }  

下面,我在為屬性添加一些標簽(Attribute):

 
 
 
 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Web.Mvc;  
  4. using System.ComponentModel.DataAnnotations;  
  5. using ContactManagerMVC.Attributes;  
  6. using System.ComponentModel;  
  7.  
  8. namespace ContactManagerMVC.Views.ViewModels  
  9. {  
  10.   public class ContactPersonViewModel  
  11.   {  
  12.     public int Id { get; set; }  
  13.     [Required(ErrorMessage = "Please provide a First Name!")]  
  14.     [StringLength(25, ErrorMessage = "First name must be less than 25 characters!")]  
  15.     [DisplayName("First Name")]  
  16.     public string FirstName { get; set; }  
  17.  
  18.     [DisplayName("Middle Name")]  
  19.     public string MiddleName { get; set; }  
  20.  
  21.     [Required(ErrorMessage = "Please provide a Last Name!")]  
  22.     [StringLength(25, ErrorMessage = "Last name must be less than 25 characters!")]  
  23.     [DisplayName("Last Name")]  
  24.     public string LastName { get; set; }  
  25.  
  26.     [Required(ErrorMessage = "You must provide a Date Of Birth!")]  
  27.     [BeforeTodaysDate(ErrorMessage = "You can't add someone who hasn't been born yet!")]  
  28.     [DisplayName("Date Of Birth")]  
  29.     public DateTime? DateOfBirth { get; set; }  
  30.  
  31.     public IEnumerable Type { get; set; }  
  32.   }  
  33. }  

上面標簽的絕大多數(shù)標簽都是在System.ComponentModel.Annotations命名空間內,只有RequiredAttribute標簽不在此命名空間內,這個標簽聲明此值必須是一個有效值,并且包含ErrorMessage屬性。這個屬性可以讓你傳入自定義錯誤信息。StringLengthAttribute標簽指定了屬性可以接受的最小值和***值范圍。當和RequiredAttribute標簽結合使用時,只需要設置可以接受的***值。DisplayNameAttribute用于設置屬性如何顯示。#p#

上面標簽中BeforeTodaysDateAttribute標簽并不是.net Framework所提供,這是一個自定義標簽,用于檢測日期是否比當前的日期要早,你可以看到ErrorMessage值被設置。這個標簽用于防止任何被添加到聯(lián)系人列表的聯(lián)系人還未出生,下面是這個標簽的代碼:

 
 
 
 
  1. using System.ComponentModel.DataAnnotations;  
  2. using System;  
  3.  
  4. namespace ContactManagerMVC.Attributes  
  5. {  
  6.   public class BeforeTodaysDateAttribute : ValidationAttribute  
  7.   {  
  8.     public override bool IsValid(object value)  
  9.     {  
  10. if (value == null)  
  11. {  
  12.   return true;  
  13. }  
  14. DateTime result;  
  15. if (DateTime.TryParse(value.ToString(), out result))  
  16. {  
  17.   if (result < DateTime.Now)  
  18.   {  
  19.     return true;  
  20.   }  
  21. }  
  22. return false;  
  23.     }  
  24.   }  
  25. }  

很簡單是吧,這個類繼承了ValidationAttribute并重寫了IsValid()虛方法,如果未提供值,或是值小于當前日期(DateTime.Now),則返回True.利用標簽(Attribute)的方式讓在一個集中的地方應用驗證規(guī)則變得簡單,現(xiàn)在,只要ContactPersonViewModel在程序中被用到了,則驗證規(guī)則同時也會被應用到。但現(xiàn)在DefaultModelBinder內的DataAnnotations被支持,下面來看新版本的Add Partial View:

 
 
 
 
  1. <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %> 
  2.  
  3.  
  4.  
  5. <% using (Html.BeginForm("Add", "Contact", FormMethod.Post, new { id = "AddContact" }))  
  6.    {%> 
  7.  
  8.   
  9.  
  10. <%= Html.LabelFor(m => m.FirstName)%>  
  11.     
  12.   
  13.  
  14.   
  15.  
  16. <%= Html.LabelFor(m => m.MiddleName)%>  
  17.     
  18.   
  19.  
  20.   
  21.  
  22. <%= Html.LabelFor(m => m.LastName)%>  
  23.     
  24.   
  25.  
  26.   
  27.  
  28. <%= Html.LabelFor(m => m.DateOfBirth)%>  
  29.     
  30.   
  31.  
  32.   
  33.  
  34.     <%= Html.LabelFor(m => m.Type)%> 
  35.     
  36.  
  37.   
  38.  
  39.   
  40.  
  41.      
  42.     
  43.  
  44.   
  45.  
  46. <%= Html.TextBox(m => m.FirstName)%>   
  47. <%= Html.ValidationMessageFor(m => m.FirstName)%>
  48. <%= Html.TextBox(m => m.MiddleName)%>
    <%= Html.TextBox(m => m.LastName)%>   
  49. <%= Html.ValidationMessageFor(m => m.LastName)%>
  50. <%= Html.TextBox(m => m.DateOfBirth)%>   
  51. <%= Html.ValidationMessageFor(m => m.DateOfBirth)%>
  52. <%= Html.DropDownList("Type")%> 
  53.     
  54.  
  55. <% } %>  

可以看出,這里使用新的強類型Html Helper.對前面項目修改的兩處是利用了jQuery代碼。***處是添加聯(lián)系人的Partial View是通過AJax提交,如果驗證失敗,則添加的form會再次被顯示,如果驗證通過,新的聯(lián)系人被添加到列表中,頁面會刷新繼而顯示更新后包含新聯(lián)系人的列表。

由于下面幾種原因,原來的Action方法需要被修正。首先修改action方法使其接受ContactPersonViewModel而不是ContactPerson作為參數(shù),這是因為相關的驗證規(guī)則應用于ContactPersonViewModel,如果不將參數(shù)類型改變,那model binder依然能將傳入的值和ContactPerson的屬性相匹配,但所有的驗證規(guī)則就不復存在了。第二個改變是檢查ModelState的IsValid屬性是否有效,否則整個驗證就變得毫無意義.

 
 
 
 
  1. [AcceptVerbs(HttpVerbs.Post)]  
  2. public ActionResult Add([Bind(Exclude = "Id, Type")]ContactPersonViewModel person)  
  3. {  
  4.  
  5.     if (ModelState.IsValid)  
  6.     {  
  7.   var p = new ContactPerson  
  8.   {  
  9. FirstName = person.FirstName,  
  10. MiddleName = person.MiddleName,  
  11. LastName = person.LastName,  
  12. Type = Request.Form["Type"].ParseEnum()  
  13.   };  
  14.   if (person.DateOfBirth != null)  
  15. p.DateOfBirth = (DateTime)person.DateOfBirth;  
  16.   ContactPersonManager.Save(p);  
  17.   return Content("Saved");  
  18.     }  
  19.     var personTypes = Enum.GetValues(typeof(PersonType))  
  20.     .Cast()  
  21.     .Select(p => new  
  22.     {  
  23.   ID = p,  
  24.   Name = p.ToString()  
  25.     });  
  26.     person.Type = new SelectList(personTypes, "ID", "Name");  
  27.     return PartialView(person);  
  28. }   
  29.  

在model綁定過程中,我去掉了id和Type屬性,因為在把聯(lián)系人添加到數(shù)據(jù)庫以前并不會存在id屬性,而去掉Type屬性是因為在ViewModel中它的類型是SelectList,但在BLL層中ContactPerson對象中卻是枚舉類型,如果ModelState的IsValid屬性為True(注:既驗證通過),則ViewModel的屬性會和ContactPerson對象的屬性進行匹配,如果IsValid不為True,數(shù)據(jù)會回傳到View中顯示驗證失敗的相關信息。

上面代碼中我們注意到了Request.Form[“Type”]這個string類型的ParseEnum擴展方法,這也是為什么我去掉Type屬性,只有這樣它才會被轉換為適當?shù)念愋?。擴展方法的原型(在我的Google Analytics 文中)如下:

 
 
 
 
  1. public static T ParseEnum(this string token)  
  2. {  
  3.     return (T)Enum.Parse(typeof(T), token);  
  4. }  
  5.  
  6. edit  

這個action方法也是如此,除了對DateOfBirth進行編輯那部分:

 
 
 
 
  1.  
  2.   <%= Html.LabelFor(m => m.DateOfBirth)%>  
  3.   <%= Html.EditorFor(m => m.DateOfBirth)%>   
  4. <%= Html.ValidationMessageFor(m => m.DateOfBirth)%>    
  5.   

這里我并沒有使用TextBoxFor擴展方法,而是使用了EditorFor方法,默認情況下,DateTime類型都以hh:mm:ss這樣的方式顯示,但我并不喜歡這種格式,所以我創(chuàng)建了一個格式化顯示時間日期的模板,在View/Shared目錄下,我添加了一個名為EditorTemplates(這也是MVC中應有命名方式,因為MVC會自動搜索這個位置)并在此目錄下添加一個名為DateTime的Partial View,這也是MVC的慣例,而DateTime.ascx的代碼如下:

 
 
 
 
  1. <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %> 
  2. <%= Html.TextBox("", Model.HasValue ? Model.Value.ToShortDateString() : string.Empty) %> 

雖然只有短短兩行代碼,但是可以讓時間日期如果為空時,什么都不顯示,而如果時間存在,則以ShortDate的格式顯示。

總結

本篇文章研究了ASP.Net MVC 2.0中利用DataAnnotations來進行驗證,現(xiàn)在這已經(jīng)是.net framework的一部分。文中還簡單的接觸了新版本中的一些特性,包括強類型的HTML Helper以及模板。本篇文章的代碼使用Visual Studio 2010 RC1創(chuàng)建的,所以代碼不能在VWD和Visual Studio的環(huán)境中調試。


當前標題:使用VisualStudio2010和MVC2.0增強驗證功能
文章分享:http://www.dlmjj.cn/article/coohdcj.html