成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

詳解ASP.NET MVC數(shù)據(jù)驗(yàn)證的一個(gè)特殊方法

開發(fā) 后端
我們這里將介紹比較特別的ASP.NET MVC數(shù)據(jù)驗(yàn)證,這項(xiàng)功能有的時(shí)候很令人費(fèi)解,希望本文能對大家更好的了解ASP.NET MVC數(shù)據(jù)驗(yàn)證有所幫助。

這里我們將介紹ASP.NET MVC數(shù)據(jù)驗(yàn)證實(shí)現(xiàn)的一個(gè)特殊方法,包括數(shù)據(jù)的驗(yàn)證,驗(yàn)證后數(shù)據(jù)的提交等等。51CTO編輯推薦《ASP.NET MVC框架視頻教程》。

關(guān)于ASP.NET MVC數(shù)據(jù)驗(yàn)證,用起來很特別,因?yàn)镸S的封裝,使人理解起來很費(fèi)解。也可能很多人都在Scott Guthrie等人寫的一本《ASP.NET MVC 1.0》書中,見過NerdDinner項(xiàng)目中對Dinner對象修改和添加的時(shí)的數(shù)據(jù)驗(yàn)證。但有許多封裝的地方,不知道是怎樣的工作原理,今天研究了,拿出來給大家分享一下。

數(shù)據(jù)庫還是上一篇blog中的庫與表,同樣的方法來創(chuàng)建news表的實(shí)體類,在自動(dòng)生成的news這個(gè)實(shí)體類中,我們發(fā)現(xiàn)有一個(gè)特殊的分部方法:

  1. partial void OnValidate(System.Data.Linq.ChangeAction action); 

這個(gè)方法沒有實(shí)現(xiàn),我們根據(jù)C#的語法知道,如果分部類中的分部方法,沒有實(shí)現(xiàn)的話,調(diào)用和定議的地方都不會(huì)起什么作用。現(xiàn)在,我們要去完善這個(gè)方法,讓它“用”起來。

首先,人產(chǎn)在Models中創(chuàng)建news類的另一部分,代碼如下:

  1.     public partial  class news  
  2.     {  
  3.         partial void OnValidate(System.Data.Linq.ChangeAction action)  
  4.         {  
  5.             if (!IsValid)  
  6.             {  
  7.                 throw new ApplicationException("驗(yàn)證內(nèi)容項(xiàng)出錯(cuò)!");  
  8.             }  
  9.         }  
  10.         public bool IsValid  
  11.         {  
  12.             get { return (GetRuleViolations().Count() == 0); }  
  13.         }  
  14.         public IEnumerable<RuleViolation> GetRuleViolations()  
  15.         {  
  16.             if (String.IsNullOrEmpty(this.title .Trim () ))  
  17.                 yield return new RuleViolation("題目步能為空!", "題目");  
  18.             if (String.IsNullOrEmpty(this.contents .Trim ()))  
  19.                 yield return new RuleViolation("內(nèi)容不能為空!", "內(nèi)容");            
  20.             yield break;  
  21.         }  
  22.     }  
  23. /// <summary> 
  24.     /// 規(guī)則信息類  
  25.     /// summary> 
  26.     public class RuleViolation  
  27.     {  
  28.         public string ErrorMessage { get; private set; }  
  29.         public string PropertyName { get; private set; }  
  30.    
  31.         public RuleViolation(string errorMessage)  
  32.         {  
  33.             ErrorMessage = errorMessage;  
  34.         }  
  35.    
  36.         public RuleViolation(string errorMessage, string propertyName)  
  37.         {  
  38.             ErrorMessage = errorMessage;  
  39.             PropertyName = propertyName;  
  40.         }  
  41.     } 

在這里給出這么多代碼,其實(shí)是提前有設(shè)計(jì)的,因?yàn)閺臉I(yè)務(wù)角度考慮,還不應(yīng)該寫這部分代碼。RuleViolation類很簡單,就是一個(gè)包括了兩個(gè)屬性的類(這個(gè)類的結(jié)構(gòu)設(shè)計(jì)是根據(jù)后面的ModelState.AddModelError主法來設(shè)計(jì)的)。

在news分部類中,有一個(gè)IsValid的屬性,這個(gè)屬性是bool類型的,返回值取決于GetRuleViolations這個(gè)方法,這個(gè)方法返回值是一個(gè)IEnumerable類型的,IEnumerable是通過news的幾個(gè)屬性是否為空來生成跌代的。如果title或contents為Null或””,就返回跌代。其實(shí)真正的用戶數(shù)據(jù)的驗(yàn)證就是在這里實(shí)現(xiàn),用戶的數(shù)據(jù)的對與錯(cuò),就是一個(gè)邏輯,只要用戶數(shù)據(jù)不符合規(guī)則,就可以 “yield return new RuleViolation("錯(cuò)誤標(biāo)識(shí)","錯(cuò)誤提示信息!")”;這里的錯(cuò)誤碼提示信息是顯示到客戶端的,所以要處理好友好的提示。

現(xiàn)在驗(yàn)證用戶數(shù)據(jù),生成錯(cuò)誤列表的工作都做完了,但關(guān)鍵是怎么能讓用戶提交數(shù)據(jù)時(shí),調(diào)用OnValidate。這個(gè)問題,先放一下,請記住,上面的代碼,只要在用戶提交數(shù)據(jù)時(shí),調(diào)用OnValidate,這樣就能得到錯(cuò)誤集合。

現(xiàn)在,讓我們來處理Cotroller和View層,在Cotroller層,首先來添加index這個(gè)Action,代碼如下:

  1. public ActionResult Index()  
  2.         {             
  3.             var NewsList = DCDC.news.Select(newss=>newss);  
  4.             return View(NewsList );  
  5.      } 

這個(gè)Action返回所有news表中的記錄。

對應(yīng)的View如下:

  1. <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage>" %> 
  2. <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> 
  3.      Index  
  4. asp:Content> 
  5. <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> 
  6.    
  7.     <h2>Indexh2> 
  8.    
  9.     <table> 
  10.         <tr> 
  11.             <th>th> 
  12.             <th> 
  13.                 ID  
  14.             th> 
  15.             <th> 
  16.                 title  
  17.             th> 
  18.             <th> 
  19.                 datetimes  
  20.             th> 
  21.             <th> 
  22.                 contents  
  23.             th> 
  24.             <th> 
  25.                 IsValid  
  26.             th> 
  27.         tr> 
  28.    
  29.     <% foreach (var item in Model) { %> 
  30.       
  31.         <tr> 
  32.             <td> 
  33.                 <%= Html.ActionLink("Edit", "Edit", new { id=item.ID }) %> |  
  34.                 <%= Html.ActionLink("Details", "Details", new { id=item.ID })%> 
  35.             td> 
  36.             <td> 
  37.                 <%= Html.Encode(item.ID) %> 
  38.             td> 
  39.             <td> 
  40.                 <%= Html.Encode(item.title) %> 
  41.             td> 
  42.             <td> 
  43.                 <%= Html.Encode(String.Format("{0:g}", item.datetimes)) %> 
  44.             td> 
  45.             <td> 
  46.                 <%= Html.Encode(item.contents) %> 
  47.             td> 
  48.             <td> 
  49.                 <%= Html.Encode(item.IsValid) %> 
  50.             td> 
  51.         tr>    
  52.     <% } %> 
  53.     table> 
  54.     <p> 
  55.         <%= Html.ActionLink("Create New", "Create") %> 
  56.     p> 
  57. asp:Content> 

代碼中,需要我們注意是的    <%= Html.ActionLink("Edit", "Edit", new { id=item.ID }) %>

因?yàn)橐獙?dǎo)航到Edit的View,把以接下來我們創(chuàng)建Edit的Action和View(因?yàn)樵诰庉嫈?shù)據(jù)時(shí),要用到驗(yàn)證,Edit才是我們的重點(diǎn))。

  1. public ActionResult Edit(int id)  
  2.         {  
  3.             var list = DCDC.news.Single(newss=>newss.ID ==id);  
  4.             return View(list);  
  5.      } 

<%= Html.ActionLink("Edit", "Edit", new { id=item.ID }) %>中的id會(huì)被當(dāng)成參數(shù)送到EditController的Edit(int id)的Action,成為Edit方法的實(shí)參。
Edit.aspx頁面如下圖:

Edit.aspx頁面

 

對應(yīng)Edit的Action生成view,代碼如下:

  1. <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %> 
  2. <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> 
  3.      編輯  
  4. asp:Content> 
  5. <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> 
  6.     <h2 style ="text-align :left ;">編輯h2> 
  7.     <%= Html.ValidationSummary("Edit was unsuccessful. Please correct the errors and try again.") %> 
  8.     <% using (Html.BeginForm())  
  9.        { %> 
  10.         <fieldset> 
  11.             <legend>詳細(xì)內(nèi)容legend>       
  12.             <p> 
  13.                 <label for="title">標(biāo)題:label> 
  14.                 <%= Html.TextBox("title", Model.title) %> 
  15.                 <%= Html.ValidationMessage("題目", "*")%> 
  16.             p> 
  17.             <p> 
  18.                 <label for="datetimes">時(shí)間:label> 
  19.                 <%= Html.TextBox("datetimes", String.Format("{0:g}", Model.datetimes)) %> 
  20.                  <%= Html.ValidationMessage("時(shí)間", "*") %> 
  21.             p> 
  22.             <p> 
  23.                 <label for="contents">內(nèi)容:label> 
  24.                 <%= Html.TextBox("contents", Model.contents) %> 
  25.                 <%= Html.ValidationMessage("內(nèi)容", "*")%> 
  26.             p> 
  27.             <p> 
  28.                 <input type="submit" value="更新" /> 
  29.             p> 
  30.         fieldset> 
  31.     <% } %> 
  32.     <div> 
  33.         <%=Html.ActionLink("Back to List", "Index") %> 
  34.     div> 
  35. asp:Content> 

如果要單擊“更新”返回?cái)?shù)據(jù)新數(shù)據(jù),還需要我們寫如下一個(gè)Action:

  1. [AcceptVerbs(HttpVerbs.Post)]  
  2.         public ActionResult Edit(int id,FormCollection formValuews)  
  3.         {  
  4.             news Sig_news = DCDC.news.Single(newss => newss.ID == id);  
  5.             try 
  6.             {                 
  7.                 Sig_news.title = formValuews.GetValue("title").AttemptedValue;  
  8.                 Sig_news.datetimes = DateTime.Parse(formValuews.GetValue("datetimes").AttemptedValue);  
  9.                 Sig_news.contents = formValuews.GetValue("contents").AttemptedValue;  
  10.                 DCDC.SubmitChanges();  
  11.                 return RedirectToAction("Index");  
  12.             }  
  13.             catch 
  14.             {  
  15.                 foreach (var v in Sig_news.GetRuleViolations())  
  16.                 {  
  17.                     ModelState.AddModelError(v.PropertyName,v.ErrorMessage);  
  18.                 }  
  19.                 return View(Sig_news);  
  20.             }  
  21.         } 

這個(gè)Edit的Action是用戶提交返來更新數(shù)據(jù)庫的,我們可以從formValuews得到用戶在頁面上更新的數(shù)據(jù),來更新Sig_news對象,然后調(diào)用DCDC.SubmitChanges();去更新數(shù)據(jù)庫,如果沒有民常,會(huì)導(dǎo)航到index.aspx頁面。如果發(fā)生異常,就會(huì)運(yùn)行到catch里。如果還記得,在本文的前半部分,我們說到OnValidate,是數(shù)據(jù)在提交時(shí)應(yīng)該驗(yàn)證,但在這里,我們并沒有顯示的調(diào)用OnValidate這個(gè)方法,但實(shí)際運(yùn)行中,我們發(fā)現(xiàn),這個(gè)方法被執(zhí)行了,如果我們建立跟蹤,把斷點(diǎn)設(shè)在DCDC.SubmitChanges();如果我們數(shù)據(jù)有民常,會(huì)發(fā)現(xiàn)當(dāng)DCDC.SubmitChanges();執(zhí)行完后就會(huì)跳到partial void OnValidate(System.Data.Linq.ChangeAction action)這個(gè)方法,這是怎么做到的呢?我們猜測,一定是在數(shù)據(jù)提交時(shí),調(diào)用OnValidate這個(gè)方法。為了找到它們的關(guān)系,只好用Reflector.exe來“探測”一下了(Reflector.exe的用法就不說了)。

SubmitChanges方法是DataContext的一個(gè)方法,這個(gè)類位于System.Data.Linq命空間下,用Reflector.exe打開SubmitChanges,看到this.SubmitChanges(ConflictMode.FailOnFirstConflict);定位這個(gè)方法,可以看到new ChangeProcessor(this.services, this).SubmitChanges(failureMode);定位查找會(huì)發(fā)現(xiàn)ValidateAll(orderedList);在這個(gè)方法中,多處看到  SendOnValidate(obj2.Type, obj2, ChangeAction.Insert);這個(gè)方法,再定位,有這樣一行代碼  type.OnValidateMethod.Invoke(item.Current, new object[] { changeAction });這里,正是通過反射調(diào)用了OnValidate這個(gè)方法。這樣我們就找到了SubmitChanges執(zhí)行時(shí)調(diào)用OnValidate的方法了(其不用調(diào)用OnValidate也可以驗(yàn)證用戶數(shù)據(jù),只需要寫個(gè)方法,在SubmitChanges 提交以前執(zhí)行就可以達(dá)到同樣效果)。同時(shí),當(dāng)發(fā)生異常時(shí),OnValidate會(huì)拋出一個(gè)Application的異常,這里會(huì)被public ActionResult Edit(int id,FormCollection formValuews)方法中的Catch捕獲到,就執(zhí)行如下代碼:

  1. foreach (var v in Sig_news.GetRuleViolations())  
  2.                 {  
  3.                     this.ModelState.AddModelError(v.PropertyName,v.ErrorMessage);  
  4.                 }  
  5.                 return View(Sig_news); 

這行代碼的意思是把錯(cuò)誤的信息,以鍵值的方式放入ModelState中,ModelState是一個(gè)ModelStateDictionary類型,這個(gè)類型實(shí)現(xiàn)了IDictionary, ICollection>, IEnumerable>, IEnumerable這些接口(這里要注意,ModelState是當(dāng)前對象的一個(gè)屬性,并且它的AddModelError方法的***個(gè)參數(shù)key有其獨(dú)特的作用)。處理完異常后,還是返回當(dāng)前頁面。這時(shí)你會(huì)發(fā)現(xiàn),在頁面的   <%= Html.ValidationSummary("Edit was unsuccessful. Please correct the errors and try again.") %>發(fā)生了變化,把我們錯(cuò)誤的地方去提示出來了,這里就是,為什么我們把錯(cuò)誤信息放到ModelState中,而錯(cuò)誤則顯示在了Html.ValidationSummary中了呢?并且發(fā)生錯(cuò)誤的數(shù)據(jù)后會(huì)加上了一個(gè)紅色的“*”,這是怎么樣做到的呢?

再次利用Reflector.exe,查看Html.ValidationSummary方法和Html.ValidationMessage方法,會(huì)發(fā)現(xiàn)它們顯示的數(shù)據(jù)是從ModelState 中獲取的,如果ModelState 這個(gè)集合中沒有數(shù)據(jù),Html.ValidationSummary和Html.ValidationMessage就返回空,如果發(fā)生異常,this.ModelState中有子項(xiàng),就會(huì)通過Html.ValidationSummary和Html.ValidationMessage在頁面頁上顯示出來。因?yàn)镠tml.ValidationMessage在頁面上有多個(gè),所以在this.ModelState.AddModelError(v.PropertyName,v.ErrorMessage);方法中的v.PropertyName就有了用處了,這個(gè)值要與<%= Html.ValidationMessage("題目", "*")%>中的***個(gè)參數(shù)對應(yīng),這樣<%= Html.ValidationMessage("題目", "*")%>才能起到作用,顯示出第二個(gè)參數(shù)“*”。
這樣一來,就達(dá)到了ASP.NET MVC的數(shù)據(jù)驗(yàn)證。由于ASP.NET MVC驗(yàn)證拐的彎比較多,所以下來用個(gè)圖來說明一下。

ASP.NET MVC驗(yàn)證圖

詳解ASP.NET MVC數(shù)據(jù)驗(yàn)證的一個(gè)特殊方法就介紹到這里。

【編輯推薦】

  1. 詳解ASP.NET MVC分頁的實(shí)現(xiàn)方法
  2. ASP.NET MVC與WebForm區(qū)別談
  3. ASP.NET MVC應(yīng)用程序執(zhí)行過程分析
  4. ASP.NET MVC分頁控件的實(shí)現(xiàn)
  5. 有關(guān)ASP.NET MVC框架的一些基礎(chǔ)知識(shí)
責(zé)任編輯:彭凡 來源: 51CTO博客
相關(guān)推薦

2009-09-18 10:20:26

PRG數(shù)據(jù)驗(yàn)證

2010-01-26 13:15:42

ASP.NET MVC

2010-03-19 09:17:16

ASP.NET MVC

2009-09-10 09:50:47

ASP.NET MVC

2009-11-24 15:11:21

ASP.NET MVC

2009-07-22 09:11:02

Action方法ASP.NET MVC

2012-08-27 10:11:43

ASP.NET

2009-08-04 16:50:26

2009-04-23 09:42:39

FubuMVCASP.NET MVCMVC

2009-10-29 09:15:32

ASP.NET MVCDropDownLis

2009-12-01 09:30:34

ASP.NET MVC

2011-04-12 13:53:25

ASP.NET MVCjQuery

2009-03-31 13:12:05

ASP.NETMVC表單驗(yàn)證

2009-07-24 13:20:44

MVC框架ASP.NET

2009-07-31 12:43:59

ASP.NET MVC

2009-07-29 12:55:44

ASP.NET身份驗(yàn)證

2009-07-22 09:36:54

使用UpdataModASP.NET MVC

2011-10-11 09:43:15

ASP.NET MVC

2011-04-14 09:19:22

ASP.NET MVC

2010-02-03 09:50:58

ASP.NET MVC
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)

主站蜘蛛池模板: 在线精品一区 | 久久av综合 | 欧美视频福利 | 日韩一二区在线 | 一区中文字幕 | av中文字幕在线 | 久久大陆| 久久成| 国产精品一区在线观看 | 色黄爽| av大全在线 | 青青久草 | 五月精品视频 | 中文字幕高清 | 天天色图 | 国产色网 | 欧美专区日韩专区 | 久久高潮 | 亚洲成人久久久 | 日韩精品a在线观看图片 | www久久99 | 久久亚洲国产精品 | 国产精品日韩欧美一区二区三区 | 视频1区2区| 性网址| 华人黄网站大全 | 日韩一区二区在线视频 | 巨大黑人极品videos精品 | 日韩欧美国产一区二区三区 | 国产日韩精品视频 | 男女污污网站 | 国产成人免费视频网站高清观看视频 | 天天拍天天射 | 精品视频久久久久久 | 69精品久久久久久 | 欧美日韩一区二区在线观看 | 国产欧美精品一区二区色综合 | 国产一区二区在线播放视频 | 亚洲国产成人精品久久久国产成人一区 | 伦理午夜电影免费观看 | 小草久久久久久久久爱六 |