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/
本文版權歸做者和博客園共有,歡迎轉載,但未經做者贊成必須保留此段聲明,且在文章頁面