前面的博客中曾经提到过ModelBing机制,也在Demo中体现过,在MVC中更吊的是封装了自定义的验证规则。下面来一个Demo来展现一下,看了后,你一定会爱上它的,能让你少写很多JS语句。
1.View层
 [html] view plaincopyprint?![]()
 
-  
<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层
 [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
 -  
{
 -  
//必填项
 -  
[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
 [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("密码错误");
 -  
}
 -  
 -  
}</span>
 
 
 
分析:整体实现的功能很简单,就是把页面传进的值通过在Controller中验证后返回结果,主要的功能就是在Model中引入了System.ComponentModel.DataAnnotations和System.ComponentModel的空间,然后为实体的属性绑定了一些自定的验证功能例如[Required]、 [DisplayName("用户别称")]、 [StringLength(6,ErrorMessage="您输入的名字太长了")]等,当然这两个命名空间中还有很多,有兴趣的可以查一下。
最终在界面上绑定强类型视图的时候,通过反射机制,自动为每个控件绑定实体属性。
 

转载于:https://blog.51cto.com/jlins/1588492