2011-10-24 24 views
1

由於一些反思-fu我想使用MVC ModelBinders將請求綁定到名稱和類型只在運行時知道的對象。ModelBinding動作中的單個參數

例如

public ActionResult BindSomething() 
{ 
    Type type = typeof(Some.Type); 
    string parameterName = "someParameter"; //this corresponds to a particular form input name 

    var binder = Binders.GetBinder(desiredType, true); 
    var x = binder.BindModel(this.ControllerContext, ???) //??? should be a ModelBindingContext. Where can I get this from 
    return View(x); 
} 

我認爲我需要得到ModelBindingContext的保持,或創建一個新的,有效的,但我要如何做到這一點?

編輯:道歉,如果我不夠清楚 - 我已經知道TryUpdateModel,但據我瞭解,它將所有發佈的值綁定到您傳入的模型對象的屬性。我只想獲得單個發佈參數的相應對象。

回答

1

您可以按照rouen的建議使用TryUpdateModel,還可以實現可以綁定正確類型的自定義模型綁定器。這種方法的優點是可以讓你處理接口或抽象模型,並讓你的綁定代碼脫離你的行爲。這有點整潔,但我只是真的推薦它,如果它將被重用在你的代碼的其他部分。