返璞歸真 asp.net mvc (8) - asp.net mvc 3.0 新特性之 Model
返璞歸真 asp.net mvc (8) - asp.net mvc 3.0 新特性之 Model
作者:webabcd
介紹
asp.net mvc 之 asp.net mvc 3.0 新特性之 Model:
- 通過 Data Annotations 與 jQuery 的結(jié)合實現(xiàn)服務(wù)端和客戶端的雙重驗證
- 雙重驗證中,使客戶端實現(xiàn)遠程的異步驗證
- 自定義 Data Annotations 與 jQuery,以實現(xiàn)自定義的雙重驗證
示例
1、Model 中通過 Data Annotations 與 jQuery 的結(jié)合實現(xiàn)服務(wù)端和客戶端的雙重驗證
Web.config
<configuration> <!-- 要實現(xiàn)服務(wù)端和客戶端的雙重驗證,需要做如下配置,因為雙重驗證中的客戶端驗證需要依賴此配置 --> <appSettings> <add key="ClientValidationEnabled" value="true"/> <add key="UnobtrusiveJavaScriptEnabled" value="true"/> </appSettings> </configuration>
User.cs
/* * 在 asp.net mvc 3.0 中支持通過 Data Annotations 來實現(xiàn)服務(wù)端和客戶端的雙重驗證,需要 jQuery 的支持 * 所有 Data Annotations 相關(guān)的 Attribute 直接用類視圖看 System.ComponentModel.DataAnnotations 就行了,詳細說明以前寫過好多遍了,這里就不重復(fù)了 * 另外 System.Web.Mvc 下有一些新增的 Data Annotations */ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Web.Mvc; namespace MVC30.Models { public class User { public int ID { get; set; } [DisplayName("名字")] [Required(ErrorMessage = "名字不能為空")] public string Name { get; set; } [DisplayName("密碼")] [Required(ErrorMessage = "密碼不能為空")] public string Password { get; set; } [DisplayName("確認密碼")] [Required(ErrorMessage = "確認密碼不能為空")] [Compare("Password", ErrorMessage="兩次密碼輸入不一致")] public string ConfirmPassword { get; set; } public DateTime DateOfBirth { get; set; } // 請求時,允許此字段包含 HTML 標記 [AllowHtml] public string Comment { get; set; } } }
ValidationDemoController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using MVC30.Models; namespace MVC30.Controllers { public class ValidationDemoController : Controller { // 用于演示通過 Data Annotations 實現(xiàn)服務(wù)端和客戶端的雙重驗證 public ActionResult Validation_DataAnnotations() { var user = new User { ID = 1, Name = "webabcd", DateOfBirth = new DateTime(1980, 2, 14), Comment = "<b>mvp</b>" }; return View(new User()); } [HttpPost] public ActionResult Validation_DataAnnotations(User user) { return View(user); } } }
Validation_DataAnnotations.cshtml
@model MVC30.Models.User @{ ViewBag.Title = "Validation_DataAnnotations"; } <h2>ClientValidation</h2> <!-- 通過 jQuery 實現(xiàn)客戶端驗證的邏輯,需要引用此 js --> <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> <!-- 服務(wù)端驗證與客戶端驗證的一一對應(yīng)需要引用此 js --> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> @* 在 MVC3 中實現(xiàn)客戶端驗證,不需要添加以下代碼 @{ Html.EnableClientValidation(); } *@ @using (Html.BeginForm()) { <fieldset> <legend>User</legend> <div class="editor-label"> @Html.LabelFor(model => model.Name) (測試方法:空著文本框,然后提交) </div> <div class="editor-field"> @Html.EditorFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name) </div> <p> <input type="submit" value="Create" /> </p> </fieldset> }
2、Model 中通過 Data Annotations 與 jQuery 的結(jié)合實現(xiàn)服務(wù)端和客戶端的雙重驗證,其中客戶端可以實現(xiàn)遠程的異步驗證
User.cs
/* * System.Web.Mvc.Remote(string action, string controller) - 讓客戶端可以通過 ajax 的方式遠程驗證 * action - 實現(xiàn)驗證邏輯的 action,即處理客戶端的異步請求的 action * controller - 實現(xiàn)驗證邏輯的 controller,即處理客戶端的異步請求的 controller */ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Web.Mvc; namespace MVC30.Models { public class User { public int ID { get; set; } [DisplayName("名字")] [Required(ErrorMessage = "名字不能為空")] [Remote("CheckUserNameExists", "ValidationDemo", ErrorMessage = "名字已存在")] public string Name { get; set; } [DisplayName("密碼")] [Required(ErrorMessage = "密碼不能為空")] public string Password { get; set; } [DisplayName("確認密碼")] [Required(ErrorMessage = "確認密碼不能為空")] [Compare("Password", ErrorMessage="兩次密碼輸入不一致")] public string ConfirmPassword { get; set; } public DateTime DateOfBirth { get; set; } // 請求時,允許此字段包含 HTML 標記 [AllowHtml] public string Comment { get; set; } } }
ValidationDemoController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using MVC30.Models; namespace MVC30.Controllers { public class ValidationDemoController : Controller { // 用于演示客戶端的遠程 ajax 異步驗證 public ActionResult Validation_Remote() { var user = new User { ID = 1, Name = "webabcd", DateOfBirth = new DateTime(1980, 2, 14), Comment = "<b>mvp</b>" }; return View(new User()); } [HttpPost] public ActionResult Validation_Remote(User user) { return View(user); } // 用于處理客戶端的異步請求,測試時請使用字符串“webabcd” [HttpGet] public ActionResult CheckUserNameExists(string name) { return Json(name != "webabcd", JsonRequestBehavior.AllowGet); } } }
Validation_Remote.cshtml
@model MVC30.Models.User @{ ViewBag.Title = "Validation_Remote"; } <h2>ClientValidation</h2> <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> @using (Html.BeginForm()) { <fieldset> <legend>User</legend> <div class="editor-label"> @Html.LabelFor(model => model.Name) (測試方法:在文本框中輸入“webabcd”) </div> <div class="editor-field"> @Html.EditorFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name) </div> <p> <input type="submit" value="Create" /> </p> </fieldset> }
3、Model 中使用更多的 Data Annotations 以及實現(xiàn)自定義的 Data Annotations 和自定義 jQuery 的相關(guān)邏輯
User.cs
/* * 如何使用更多的 Data Annotation * 1、在“Tools”中選擇“Extension Manager”(安裝 NuGet 后會有此選項) * 2、搜索“DataAnnotationsExtensions”,然后安裝“DataAnnotationsExtensions.MVC3”項目 * 3、之后就可以使用此項目所支持的多個新的 Data Annotation * 如何自定義 Data Annotation * 詳見:IntegerAttribute.cs */ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Web.Mvc; namespace MVC30.Models { public class User { public int ID { get; set; } [DisplayName("名字")] [Required(ErrorMessage = "名字不能為空")] [Remote("CheckUserNameExists", "ValidationDemo", ErrorMessage = "名字已存在")] public string Name { get; set; } [DisplayName("密碼")] [Required(ErrorMessage = "密碼不能為空")] [Integer(ErrorMessage = "密碼必須是整型")] public string Password { get; set; } [DisplayName("確認密碼")] [Required(ErrorMessage = "確認密碼不能為空")] [Compare("Password", ErrorMessage="兩次密碼輸入不一致")] public string ConfirmPassword { get; set; } public DateTime DateOfBirth { get; set; } // 請求時,允許此字段包含 HTML 標記 [AllowHtml] public string Comment { get; set; } } }
IntegerAttribute.cs
/* * 自定義 Data Annotation,以實現(xiàn)與 jQuery 結(jié)合的客戶端和服務(wù)端雙重驗證 */ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; using System.Text.RegularExpressions; using System.Web.Mvc; namespace MVC30.Models { // 繼承 ValidationAttribute 抽象類,重寫 IsValid() 方法,以實現(xiàn)服務(wù)端驗證 // 實現(xiàn) IClientValidatable 接口的 GetClientValidationRules() 方法,以實現(xiàn)客戶端驗證 public class IntegerAttribute : ValidationAttribute, IClientValidatable { // 服務(wù)端驗證邏輯,判斷輸入是否為整型 public override bool IsValid(object value) { var number = Convert.ToString(value); return Regex.IsMatch(number, @"^[0-9]+$"); } // 客戶端驗證邏輯,需要結(jié)合客戶端驗證代碼,詳見 Validation_Custom.cshtml 文件 public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { var rule = new ModelClientValidationRule { ErrorMessage = this.ErrorMessage, // ValidationType - 指定一個 key(字符串),該 key 用于關(guān)聯(lián)服務(wù)端驗證邏輯與客戶端驗證邏輯。注:這個 key 必須都是由小寫字母組成 ValidationType = "isinteger" }; // 向客戶端驗證代碼傳遞參數(shù) rule.ValidationParameters.Add("param1", "value1"); rule.ValidationParameters.Add("param2", "value2"); yield return rule; } } }
ValidationDemoController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using MVC30.Models; namespace MVC30.Controllers { public class ValidationDemoController : Controller { // 用于演示如何使用更多的 Data Annotations 來實現(xiàn)服務(wù)端和客戶端的雙重驗證,以及如何自定義 Data Annotations 來實現(xiàn)服務(wù)端和客戶端的雙重驗證 public ActionResult Validation_Custom() { var user = new User { ID = 1, Name = "webabcd", DateOfBirth = new DateTime(1980, 2, 14), Comment = "<b>mvp</b>" }; return View(new User()); } [HttpPost] public ActionResult Validation_Custom(User user) { return View(user); } } }
Validation_Custom.cshtml
@model MVC30.Models.User @{ ViewBag.Title = "ClientValidation"; } <h2>ClientValidation</h2> <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> <script type="text/javascript"> // 客戶端驗證邏輯,判斷輸入是否為整型 jQuery.validator.addMethod( 'checkInteger', function (value, element) { var reg = new RegExp("^[0-9]+$"); return (reg.test(value)); } ); // 將客戶端驗證邏輯通過 ValidationType 與服務(wù)端的相關(guān)驗證邏輯結(jié)合起來 jQuery.validator.unobtrusive.adapters.add( 'isinteger', // ValidationType,必須全為小寫 ['param1', 'param2'], // 接收 ModelClientValidationRule 中的參數(shù)信息 function (options) { options.rules['checkInteger'] = true; // 啟用名為 checkInteger 的客戶端驗證邏輯 options.messages['checkInteger'] = options.message; // 發(fā)生驗證錯誤后的顯示信息 var param1 = options.params.param1; // ModelClientValidationRule 中的參數(shù)信息 var param2 = options.params.param2; // ModelClientValidationRule 中的參數(shù)信息 alert(param1 + " " + param2); } ); </script> @using (Html.BeginForm()) { <fieldset> <legend>User</legend> <div class="editor-label"> @Html.LabelFor(model => model.Name) </div> <div class="editor-field"> @Html.EditorFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name) </div> <div class="editor-label"> @Html.LabelFor(model => model.Password) (測試方法:在文本框中輸入非整型的字符串) </div> <div class="editor-field"> @Html.EditorFor(model => model.Password) @Html.ValidationMessageFor(model => model.Password) </div> <p> <input type="submit" value="Create" /> </p> </fieldset> }
OK
[源碼下載]
浙公網(wǎng)安備 33010602011771號