我想了解自定義綁定應該如何工作。使用DefaultModelBinder自定義模型綁定
假設
[HttpPost]
public ActionResult MyAction(CustomType parameter) {
// do something
}
一個簡單的動作......和下面的表單數據
{
parameter : "mydata"
parameter.Property1 : "something"
parameter.Property2 : 3
}
...及以下,非常簡單的定製綁定
public class MyBinder : DefaultModelBinder {
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
if (bindingContext.ModelType.Equals(typeof(CustomType))) {
string parameter = controllerContext.HttpContext.Request.Form[bindingContext.ModelName];
object model = controllerContext.HttpContext.Cache[parameter];
return model;
}
return base.BindModel(controllerContext, bindingContext);
}
protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) {
// not called
return base.CreateModel(controllerContext, bindingContext, modelType);
}
protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor) {
// not called
base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
}
}
我可以看到BindModel
方法被調用。但是,一旦我返回自定義對象,BindProperty
方法永遠不會被調用Property1
和Property2
。這很有道理,因爲我不打電話給base.BindModel()
。
所以我的問題是:如何應該BindModel
被實現,它創造CustomType
還呼籲在超類BindModel
?
是什麼讓你覺得你需要一個自定義的模型綁定器。您發佈的數據與您的模型沒有任何關係。事實上,你有'參數:「mydata」'意味着模型綁定過程中發生的第一件事是'CustomType'類型的新實例被初始化,然後它試圖設置'CustomType =「mydata」的值當然會失敗(你不能將一個複雜的對象設置爲一個字符串)。發佈的數據需要是'{Property1:'something,Property2:3}',DefaultModelBinder會初始化一個新的CustomType並設置Property1和Property2的值。 –
@StephenMuecke是的,你是對的,我爲這個人爲的例子道歉。請考慮一個場景,其中'parameter:「mydata」'包含與創建對象有關的有用數據,例如持有exise對象的字典的鍵或對象的串行表示。然後我想通過默認綁定器提供的遞歸屬性綁定來跟蹤這個對象檢索。我希望這個問題更清楚。 –