MVC中的验证规则
前面的博客中曾經(jīng)提到過(guò)ModelBing機(jī)制,也在Demo中體現(xiàn)過(guò),在MVC中更吊的是封裝了自定義的驗(yàn)證規(guī)則。下面來(lái)一個(gè)Demo來(lái)展現(xiàn)一下,看了后,你一定會(huì)愛(ài)上它的,能讓你少寫很多JS語(yǔ)句。
1.View層
?
[html]?view plaincopyprint?
<span?style="font-size:18px;">@*自動(dòng)綁定實(shí)體模型*@??
@model?MvcApplication1.Models.User??
??
??
<h2>Login</h2>??
<form?method="post">??
????@*綁定實(shí)體顯示名稱*@??
????@Html.LabelFor(user=>user.ID)??
????@*綁定實(shí)體值*@??
????@Html.TextBoxFor(user?=>?user.ID)???
????@*驗(yàn)證規(guī)則*@?????
????@Html.ValidationMessageFor(user?=>?user.ID)<br?/>??
????@Html.LabelFor(user=>user.Password)??
????@Html.EditorFor(user?=>?user.Password)??
????@Html.ValidationMessageFor(user?=>?user.Password)<br?/>??
????<input?type="submit"?name="提交"?/>??
</form>??
?????
??
</span>??
2.Model層
?
[csharp]?view plaincopyprint?
<span?style="font-size:18px;">using?System;??
using?System.Collections.Generic;??
using?System.Linq;??
using?System.Web;??
using?System.ComponentModel.DataAnnotations;??
using?System.ComponentModel;??
??
namespace?MvcApplication1.Models??
{??
????public?class?User??
????{??
????????//必填項(xiàng)??
????????[Required]??
????????//界面綁定的名稱??
???????[DisplayName("用戶別稱")]??
????????//限制字符的長(zhǎng)度??
????????[StringLength(6,ErrorMessage="您輸入的名字太長(zhǎng)了")]??
????????//綁定的類型??
????????[DataType(DataType.Text)]??
?????????
????????//[Range(555555,999999)]??
????????public?string?ID?{?get;?set;?}??
????????[Required]??
????????[DataType(DataType.Password)]??
????????[DisplayName("用戶密碼")]??
????????public?string?Password?{?get;?set;?}??
????}??
}</span>??
3.Controller
?
[csharp]?view plaincopyprint?
<span?style="font-size:18px;">?public?ActionResult?Login()??
????????{??
????????????return?View();??
????????}??
??
????????[HttpPost]??
????????public?ActionResult?Login(User?user)??
????????{??
????????????if?(user.ID?=="Admin"?||?user.Password?==?"Admin")??
????????????{??
????????????????return?Content("登錄成功");??
????????????}??
????????????else??
????????????{??
????????????????return?Content("密碼錯(cuò)誤");??
????????????}??
?????????????
????????}</span>??
分析:整體實(shí)現(xiàn)的功能很簡(jiǎn)單,就是把頁(yè)面?zhèn)鬟M(jìn)的值通過(guò)在Controller中驗(yàn)證后返回結(jié)果,主要的功能就是在Model中引入了System.ComponentModel.DataAnnotations和System.ComponentModel的空間,然后為實(shí)體的屬性綁定了一些自定的驗(yàn)證功能例如[Required]、 [DisplayName("用戶別稱")]、 [StringLength(6,ErrorMessage="您輸入的名字太長(zhǎng)了")]等,當(dāng)然這兩個(gè)命名空間中還有很多,有興趣的可以查一下。
?最終在界面上綁定強(qiáng)類型視圖的時(shí)候,通過(guò)反射機(jī)制,自動(dòng)為每個(gè)控件綁定實(shí)體屬性。
轉(zhuǎn)載于:https://blog.51cto.com/jlins/1588492
總結(jié)
- 上一篇: 第十六周项目3-有相同数字?
- 下一篇: C++的enum hack