這是錯誤的在許多層面上恕我直言:
- 這不是ASP.NET MVC是如何設計工作。
- 你的行爲沒有定義他們期望的數據的明確合同。
- 你從中得到什麼?聞起來像不好的設計。
模型綁定是由反射驅動的。在調用動作之前,它將反映方法參數列表,並且爲每個對象及其屬性調用模型聯編程序,以便爲來自各個值提供程序(表單POST值提供程序,url參數等)的每個屬性查找值。在模型綁定過程中,ModelState驗證也完成。
因此,通過不使用默認的ASP.NET MVC來做到這一點,你正在失去所有這一切。
即使你是手動得到一個模型綁定這樣的保持:
IModelBinder modelBinder = ModelBinders.Binders.GetBinder(typeof(MyObject));
MyObject myObject = (MyObject) modelBinder.BindModel(this.ControllerContext, ** ModelBindingContext HERE**);
你可以看到,你需要一個initalize ModelBindingContext,一些ASP.NET MVC會做內部基於當前它反映的財產。
protected virtual object GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) {
// collect all of the necessary binding properties
Type parameterType = parameterDescriptor.ParameterType;
IModelBinder binder = GetModelBinder(parameterDescriptor);
IDictionary<string, ValueProviderResult> valueProvider = controllerContext.Controller.ValueProvider;
string parameterName = parameterDescriptor.BindingInfo.Prefix ?? parameterDescriptor.ParameterName;
Predicate<string> propertyFilter = GetPropertyFilter(parameterDescriptor);
// finally, call into the binder
ModelBindingContext bindingContext = new ModelBindingContext() {
FallbackToEmptyPrefix = (parameterDescriptor.BindingInfo.Prefix == null), // only fall back if prefix not specified
ModelName = parameterName,
ModelState = controllerContext.Controller.ViewData.ModelState,
ModelType = parameterType,
PropertyFilter = propertyFilter,
ValueProvider = valueProvider
};
object result = binder.BindModel(controllerContext, bindingContext);
return result;
}
'你從中得到什麼?聞起來像糟糕的設計。「看起來像一個糟糕的設計綁定到多個模型類型,但它有一個很好的性能使用。你可以先注入所有被初始化的東西,然後做一個警戒子句並儘早返回,而不是使用已經設置好的注入對象。或者,在守衛子句之後,一旦確定要使用某個對象,請使用'UpdateModel'來解析依賴關係。這很麻煩,但如果你必須進行設計交易以達到性能,這是一種可能性。 – StuperUser