|
Model Binder在ASP.NET MVC中非常簡(jiǎn)單。簡(jiǎn)單的說(shuō)就是你控制器中的Action方法需要參數(shù)數(shù)據(jù);而這些參數(shù)數(shù)據(jù)包含在HTTP請(qǐng)求中,包括表單上的Value和URL中的參數(shù)等。而ModelBinder的功能就是將這些個(gè)表單上的Value和URL中的參數(shù)換成對(duì)象,然后將這些對(duì)象綁定到Action的參數(shù)上面。我簡(jiǎn)單的畫了一個(gè)圖,看起來(lái)會(huì)更加直觀。
[HttpPost]
public ActionResult Create()
{
Book book = new Book();
book.Title = Request.Form["Title"];
// ...
return View();
}
但是這樣的寫法是非常不可取的,因?yàn)榇a不容易閱讀,也不易測(cè)試。再看下面的寫法:
[HttpPost]
public ActionResult Create(FormCollection values)
{
Book book = new Book();
book.Title = values["Sex"];
// ...
return View();
}
這樣的寫法就可以不用從Request中獲取數(shù)據(jù)了,這樣能滿足一些情況,比直接從Request中獲取數(shù)據(jù)要直觀。但是如果在Action需要的數(shù)據(jù)既要來(lái)自表單上的值,又要來(lái)自URL的query string。這種情況單單FormCollection是不行的。看下面代碼:
[HttpPost]
public ActionResult Create(Book book)
{
// ...
return View();
}
上面的代碼就非常的直觀了,這需要我們的model binder創(chuàng)建一個(gè)book對(duì)象,然后直接從這個(gè)對(duì)象的屬性中取值。這個(gè)book對(duì)象的數(shù)據(jù)自然也是來(lái)自Form和URL。有時(shí)候,我們的DefaultModelBinder轉(zhuǎn)換的能力必經(jīng)有限,也不夠透明化,一些特殊和復(fù)雜的情況就需要我們自定義Model Binder。下面我講講如何去自定義Model Binder。
1、首先我們定義一個(gè)Book的實(shí)體類:
public class Book
{
public string Title { get; set; }
public string Author { get; set; }
public DateTime DatePublished { get; set; }
}
2、自定義的model binder需要繼承IModelBinder或者它的子類。數(shù)據(jù)可以從bindingContext獲取。
public class BookModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var book = (Book)(bindingContext.Model ?? new Book());
book.Title = GetValue<string>(bindingContext, "Title");
book.Author = GetValue<string>(bindingContext, "Author");
book.DatePublished = GetValue<DateTime>(bindingContext, "DatePublished");
if (String.IsNullOrEmpty(book.Title))
{
bindingContext.ModelState.AddModelError("Title", "書名不能為空?");
}
return book;
}
private T GetValue<T>(ModelBindingContext bindingContext, string key)
{
ValueProviderResult valueResult= bindingContext.ValueProvider.GetValue(key);
bindingContext.ModelState.SetModelValue(key, valueResult);
return (T)valueResult.ConvertTo(typeof(T));
}
}
從上面代碼可以看出,自定義的ModelBinde非常的自由,可以自由的將Form上的一個(gè)key對(duì)應(yīng)實(shí)體的一個(gè)屬性,也可以加入一些驗(yàn)證的邏輯。當(dāng)然還可以加入一些其他的自定義邏輯。
3、寫好BookModelBinder之后,我們只需要簡(jiǎn)單的注冊(cè)一下就行了,在Global.asax添加下面代碼:
ModelBinders.Binders.Add(typeof(Book), new BookModelBinder());
總結(jié):本文簡(jiǎn)單介紹了一下ASP.NET MVC的Model Binder機(jī)制。如果敘述有問題,歡迎指正。
NET技術(shù):ASP.NET MVC 2擴(kuò)展點(diǎn)之Model Binder,轉(zhuǎn)載需保留來(lái)源!
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請(qǐng)第一時(shí)間聯(lián)系我們修改或刪除,多謝。