扬中网站制作,郑州制作网页的公司,网站做百度百科,网站开发的三个流程前面的博客中曾经提到过ModelBing机制#xff0c;也在Demo中体现过#xff0c;在MVC中更吊的是封装了自定义的验证规则。下面来一个Demo来展现一下#xff0c;看了后#xff0c;你一定会爱上它的#xff0c;能让你少写很多JS语句。 1.View层 [html] view plaincopyprint… 前面的博客中曾经提到过ModelBing机制也在Demo中体现过在MVC中更吊的是封装了自定义的验证规则。下面来一个Demo来展现一下看了后你一定会爱上它的能让你少写很多JS语句。 1.View层 [html] view plaincopyprint? span stylefont-size:18px;*自动绑定实体模型* model MvcApplication1.Models.User h2Login/h2 form methodpost *绑定实体显示名称* Html.LabelFor(useruser.ID) *绑定实体值* Html.TextBoxFor(user user.ID) *验证规则* Html.ValidationMessageFor(user user.ID)br / Html.LabelFor(useruser.Password) Html.EditorFor(user user.Password) Html.ValidationMessageFor(user user.Password)br / input typesubmit name提交 / /form /span 2.Model层 [csharp] view plaincopyprint? span stylefont-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 stylefont-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您输入的名字太长了)]等当然这两个命名空间中还有很多有兴趣的可以查一下。 最终在界面上绑定强类型视图的时候通过反射机制自动为每个控件绑定实体属性。 萌萌的IT人 转载于:https://blog.51cto.com/jlins/1588492