ModelMetadata系列的结束了,从本篇开始就进入Model绑定部分了,这个系列阅读事后你会对Model绑定有个比较清楚的了解, 本篇对于Model绑定器的最基础的应用做个简单的示例展现,目的在于让你们事先了解一下Model绑定器是什么样的便于后续篇幅的理解。框架
Model绑定器在前面的篇幅示例中也有涉及到,在本篇中从新讲一下,看过前面篇幅的朋友能够大概的浏览一下本篇,而后跳至下一篇了。ide
对于Model绑定器系统提供了一个默认的绑定器DefaultModelBinder类型,而它实现了IModelBinder接口,咱们来看一下IModelBinder接口的定义,代码1-1.测试
代码1-1spa
public interface IModelBinder { // 摘要: // 使用指定的控制器上下文和绑定上下文将模型绑定到一个值。 // // 参数: // controllerContext: // 控制器上下文。 // // bindingContext: // 绑定上下文。 // // 返回结果: // 绑定值。 object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext); }
看到代码1-1中,IModelBinder接口中定义了一个BindModel()方法,而且有两个参数,经过系统提供给咱们的注释了解到,一个是控制器上下文对象,还有一个是绑定器上下文对象,控制器上下文对象的意思就是在当前控制器所执行范围内的全部基础信息都包含在其中,同理绑定上下文也是。后续的篇幅会对这一系列的上下文对象做详细的介绍,这里就带过了。code
如今咱们来实现IModelBinder接口定义个本身的Model绑定器,固然了也能够继承自DefaultModelBinder类型重写一下BindModel()方法。咱们来看一下咱们的自定义实现,代码1-2.对象
代码1-2blog
using System.Web.Mvc; using ConsoleApplication2; namespace MvcApplication.Binders { public class MyCustomModelBinder:IModelBinder { public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { return new Customer() { CustomerID = "010", Name = "测试人员", RegistrationDate = DateTime.Now, Address = new Address() { AddressName = "天空之城" } }; } } }
对于ConsoleApplication2命名空间的引用是由于ViewModel被定义在了那里,也就是代码1-2中BindModel()方法所要返回的类型,在代码1-2中咱们只是简单的实例化了一个ViewModel(Customer类型),实际能够作的操做很是多。咱们再看一下ViewModel的定义,代码1-3。继承
代码1-3接口
public class Customer { [HiddenInput(DisplayValue=false)] public string CustomerID { get; set; } [Display(Name="姓名")] [UIHint("Password")] public string Name { get; set; } [DataType(DataType.Date)] [Display(Name="注册日期")] public DateTime RegistrationDate{ get; set; } [UIHint("Address")] public Address Address { get; set; } } public class Address { [Display(Name="地址名称")] [MyCustomMetadataAware] public string AddressName { get; set; } }
代码1-3就是ViewModel的定义了,其中包含的一些信息有不清楚的能够在看完本篇后去看ASP.NET MVC Model元数据系列。get
如今咱们看一下控制器方法的定义,代码1-4.
代码1-4
public ViewResult Show(Customer customer) { return View(customer); }
为何ViewModel要以做为控制器方法参数的方式来进行Model绑定呢?这个疑问在下篇中会解决。
看一下代码1-5,做为Show方法对应视图的代码:
代码1-5
@model ConsoleApplication2.Customer @{ ViewBag.Title = "Show"; } <h2>Show</h2> <p>@Html.EditorForModel()</p> <p>@Html.EditorFor(m=>Model.Address)</p>
这样就完成了基础的工做了,不过仍是运行不了,由于咱们自定义的Model绑定器尚未定义到系统中,在项目的Global.asax文件中的MvcApplication类型的Application_Start()方法中添加如代码1-6。
代码1-6
ModelBinders.Binders.Add(typeof(Customer), new Binders.MyCustomModelBinder());
固然了也不限于在这里添加,只要在受权过滤器执行以前的任何一个地方都行,由于在受权过滤器执行事后便会对Model绑定器进行生成了,下篇会有讲解。在这里添加只不过这里是MVC最早执行的地方。如今咱们运行查看结果了。
图1
做者:金源
出处:http://www.cnblogs.com/jin-yuan/
本文版权归做者和博客园共有,欢迎转载,但未经做者赞成必须保留此段声明,且在文章页面