標籤:des style blog http color io 使用 ar strong
Model綁定是指從URL提取資料,產生對應Action方法的參數這個過程。前面介紹的一系列Descriptor負責提供了控制器,行為方法和參數的中繼資料,ValueProvieder負責擷取資料,剩下的Moder綁定則是利用上述兩者的結果來最終達到Model的產生。ParameterDescriptor裡面的BindingInfo(類型是ParameterBindingInfo)的Binder是一個實現了IModelBinder介面的對象,ModelBinder組件用於真正的Model綁定。
ModelBinder組件
下面則先看組件的類圖
IModelBinder:BindModel方法,實現Model綁定功能的方法,傳入ControllerContext和ModelBindingContext返回綁定完畢的Model。
CustomModelBinderAttribute:抽象特性,完成Model與ModelBinder之間的綁定處理,裡面的GetBinder方法用於擷取ModelBinder。
ModelBinderAttribute:CustomModelBinderAttribute的唯一繼承,可用於參數,介面,枚舉,結構,類的特性中,但是只有作為Action方法的參數特性時才會在ParameterDescriptor解析的時候解析出來。
IModelBinderProvider:MVC架構中沒有一個類實現這個介面,主要用於進行自訂擴充。GetBinder方法用於按指定類型擷取ModelBinder。
ModelBinderProviderCollection:對於IModelBinderProvider的一個集合。
ModelBinderProviders:擁有唯讀屬性BinderProviders,是ModelBinderProviderCollection類型。
ModelBinderDictionray:IModelBinder的字典集合,以Model的資料類型Type為Key,對應的ModelBinder為Value的字典集。
ModelBinders:具有Binders的唯讀屬性,類型是ModelBinderDictionray,只用於擷取ModelBinderDictionray。
擷取ModelBinders的機制:它一般是先從ParameterDescription裡面檢查ModelBinder是否存在,如果該ModelBinder不存在,就使用ModelBinders.Binders屬性中擷取,實際上是從ModelBinderDictionary的內部集合_innerDictionary或_modelBinderProviders中擷取;如果在上述兩個集合中也無法擷取,則使用ModelBinderDictionary中的預設MolderBinder——_defaultBinder。
按照上述的擷取機制,在定製資料類型的ModelBinder時,使用不同的方式,ModelBinder擷取時也會有不同的優先順序:
1)為Action方法上的參數加上ModelBinderAttribute或CustomModelBinderAttribute特性;
2)自訂ModelBinderProvider未某種Model資料提供ModelBinder,使用ModelBinderProviders.BinderProviders.Add方法添加到集合中去
3)為Model類型加上ModelBinderAttribute或CustomModelBinderAttribute特性
4)通過ModelBinders的Binders屬性添加ModelBinder。
ModelState
Model綁定除了把值綁定到Action方法的參數上,同樣也會綁定到Controller的ViewData中,則是列舉了ModelState相關的類。
ModelBindingContext
ModelBindingContext:具有一系列來自於ParameterDescriptor的屬性。ModelBinderContext的產生以及發揮作用如所示
ASP.NET MVC Model綁定小結