標籤:style blog http io ar os sp for on
前面的部落格中曾經提到過ModelBing機制,也在Demo中體現過,在MVC中更吊的是封裝了自訂的驗證規則。下面來一個Demo來展現一下,看了後,你一定會愛上它的,能讓你少寫很多JS語句。
1.View層
<span style="font-size:18px;">@*自動綁定實體模型*@@model MvcApplication1.Models.User<h2>Login</h2><form method="post"> @*綁定實體顯示名稱*@ @Html.LabelFor(user=>user.ID) @*綁定實體值*@ @Html.TextBoxFor(user => user.ID) @*驗證規則*@ @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層
<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 { //必填項 [Required] //介面綁定的名稱 [DisplayName("使用者別稱")] //限制字元的長度 [StringLength(6,ErrorMessage="您輸入的名字太長了")] //綁定的類型 [DataType(DataType.Text)] //[Range(555555,999999)] public string ID { get; set; } [Required] [DataType(DataType.Password)] [DisplayName("使用者密碼")] public string Password { get; set; } }}</span>
3.Controller
<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("密碼錯誤"); } }</span>
分析:整體實現的功能很簡單,就是把頁面傳進的值通過在Controller中驗證後返回結果,主要的功能就是在Model中引入了System.ComponentModel.DataAnnotations和System.ComponentModel的空間,然後為實體的屬性綁定了一些自定的驗證功能例如[Required]、 [DisplayName("使用者別稱")]、 [StringLength(6,ErrorMessage="您輸入的名字太長了")]等,當然這兩個命名空間中還有很多,有興趣的可以查一下。
最終在介面上綁定強型別視圖的時候,通過反射機制,自動為每個控制項綁定實體屬性。
MVC中的驗證規則