標籤:
什麼是ModelBinder
ASP.NET MVC中,所有的請求最終都會到達某個Controller中的某個Action並由該Action負責具體的處理和響應。為了能夠正確處理請求,Action的參數(如果有的話),必須在Action執行之前,根據相應的規則,把請求中所包含的資料提取出來並將映射為Action的參數值,這個過程就是ModelBinder。ModelBinder的作用就是為Action提供參數列表。
ModelBinder的好處
- 使代碼變得更加簡潔
- 協助我們擷取HTTP請求中的資料
- 協助我們完成必要的資料類型轉換
ASP.NET MVC中ModelBinder的實現過程
ASP.NET MVC中ModelBinder的實現過程比較複雜,這裡簡要說明它的總體流程。具體的實現過程可以看蔣金楠的《ASP.NET MVC5架構揭秘》或者看他的部落格How ASP.NET MVC Works?,講解很詳細。
ASP.NET MVC5 ModelBinder.png
- HTTP請求中的資料可能存在於querystring中,也可能在表單中,也有可能是JSON字串。究竟從哪裡擷取資料,這要依賴於參數的描述資訊
ParameterDescriptor
ParameterDescriptor的擷取需要藉助於ControllerDescriptor和ActionDescriptor,它們分別用來描述Controller和Action
IModelBinderProvider用於提供合適的ModelBinder對象,我們可以自己實現該介面以擷取自訂的IModelBinder
- ModelBinder的核心是
IModelBinder,預設實作類別是DefaultModelBinder,我們可以自己實現IModelBinder介面來擴充ModelBinder
IValueProvider針對不同的資料來源提供了資料的訪問機制
ValueProviderResult提供了兩個ConvertTo方法重載以實現向指定目標類型的轉換。
- 經過上述一系列的處理擷取最終結果
自訂ModelBinder
自訂Modelbinder只需實現System.Web.Mvc.IModelBinder介面即可。這裡需要注意一點,System.Web.ModelBinding命名空間下也有一個IModelBinder介面,不要搞錯了。
public class LessonEditInfoViewModelBinder : IModelBinder{ //根據前台傳遞的id值擷取對象 public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { var idStr = controllerContext.HttpContext.Request["id"] ?? controllerContext.RouteData.Values["id"]?.ToString(); int id = 0; if (!int.TryParse(idStr, out id)) { return null; } var model = new LessonBLL().GetLessonEditInfo(id); return model; }}
然後使用ModelBinderAttribute進行標註即可:
/* 根據前台傳遞的id值解析出對象資料,Action無需關注對象的擷取,使代碼變得清晰簡潔*/public ActionResult Edit([ModelBinder(typeof(LessonEditInfoViewModelBinder))]LessonEditInfoViewModel lesson){ if (lesson == null) { //跨控制器的視圖跳轉要使用視圖的路徑+檔案名稱 return View("/Views/Exception/GenericError.cshtml", new ExceptionViewModel { Title = "404", Description = "課程不存在!" }); } return View(lesson);}
如果項目中多出需要使用自訂的ModelBinder,那麼再使用ModelBinderAttribute進行標註就不大合適了。這種情況我們可以使用自訂的ModelBinderProvier。代碼如下:
public class CustomeModelBinderProvider : IModelBinderProvider{ public IModelBinder GetBinder(Type modelType) { if (modelType == typeof(LessonEditInfoViewModel)) { return new LessonEditInfoViewModelBinder(); } return null; }}
然後將自訂的ModelBinderProvider註冊到ASP.NET MVC系統中
public class MvcApplication : System.Web.HttpApplication{ protected void Application_Start() { ModelBinderProviders.BinderProviders.Insert(0, new CustomeModelBinderProvider()); }}
完成上述兩步之後,就無需使用ModelBuilderAttribute進行標註了。
參考文章:
Model Binders in ASP.NET MVC
ModelBinder——ASP.NET MVC Model綁定的核心
ASP.NET MVC以ValueProvider為核心的值提供系統
玩轉Asp.net MVC 的八個擴充點
ASP.NET MVC中你必須知道的13個擴充點
著作權聲明
本文為作者原創,著作權歸作者雪飛鴻所有。 轉載必須保留文章的完整性,且在頁面明顯位置處標明原文連結。
如有問題, 請發送郵件和作者聯絡。
ASP.NET MVC5 ModelBinder