前面的博客中曾经提到过ModelBing机制,也在Demo中体现过,在MVC中更吊的是封装了自定义的验证规则。下面来一个Demo来展现一下,看了后,你一定会爱上它的,能让你少写很多JS语句。

1.View层

 

[html] view plaincopyprint?在CODE上查看代码片派生到我的代码片

  1. <span style="font-size:18px;">@*自动绑定实体模型*@  

  2. @model MvcApplication1.Models.User  

  3.   

  4.   

  5. <h2>Login</h2>  

  6. <form method="post">  

  7.     @*绑定实体显示名称*@  

  8.     @Html.LabelFor(user=>user.ID)  

  9.     @*绑定实体值*@  

  10.     @Html.TextBoxFor(user => user.ID)   

  11.     @*验证规则*@     

  12.     @Html.ValidationMessageFor(user => user.ID)<br />  

  13.     @Html.LabelFor(user=>user.Password)  

  14.     @Html.EditorFor(user => user.Password)  

  15.     @Html.ValidationMessageFor(user => user.Password)<br />  

  16.     <input type="submit" name="提交" />  

  17. </form>  

  18.      

  19.   

  20. </span>  


2.Model层

 

[csharp] view plaincopyprint?在CODE上查看代码片派生到我的代码片

  1. <span style="font-size:18px;">using System;  

  2. using System.Collections.Generic;  

  3. using System.Linq;  

  4. using System.Web;  

  5. using System.ComponentModel.DataAnnotations;  

  6. using System.ComponentModel;  

  7.   

  8. namespace MvcApplication1.Models  

  9. {  

  10.     public class User  

  11.     {  

  12.         //必填项  

  13.         [Required]  

  14.         //界面绑定的名称  

  15.        [DisplayName("用户别称")]  

  16.         //限制字符的长度  

  17.         [StringLength(6,ErrorMessage="您输入的名字太长了")]  

  18.         //绑定的类型  

  19.         [DataType(DataType.Text)]  

  20.          

  21.         //[Range(555555,999999)]  

  22.         public string ID { getset; }  

  23.         [Required]  

  24.         [DataType(DataType.Password)]  

  25.         [DisplayName("用户密码")]  

  26.         public string Password { getset; }  

  27.     }  

  28. }</span>  


3.Controller

 

[csharp] view plaincopyprint?在CODE上查看代码片派生到我的代码片

  1. <span style="font-size:18px;"public ActionResult Login()  

  2.         {  

  3.             return View();  

  4.         }  

  5.   

  6.         [HttpPost]  

  7.         public ActionResult Login(User user)  

  8.         {  

  9.             if (user.ID =="Admin" || user.Password == "Admin")  

  10.             {  

  11.                 return Content("登录成功");  

  12.             }  

  13.             else  

  14.             {  

  15.                 return Content("密码错误");  

  16.             }  

  17.              

  18.         }</span>  



分析:整体实现的功能很简单,就是把页面传进的值通过在Controller中验证后返回结果,主要的功能就是在Model中引入了System.ComponentModel.DataAnnotations和System.ComponentModel的空间,然后为实体的属性绑定了一些自定的验证功能例如[Required]、 [DisplayName("用户别称")]、 [StringLength(6,ErrorMessage="您输入的名字太长了")]等,当然这两个命名空间中还有很多,有兴趣的可以查一下。

 最终在界面上绑定强类型视图的时候,通过反射机制,自动为每个控件绑定实体属性。


萌萌的IT人