ModelBinding Action中的单个参数

时间:2011-10-24 10:27:20

标签: asp.net-mvc model-binding

由于一些反思,我希望使用MVC ModelBinder将请求绑定到一个名称和类型的对象,该对象仅在运行时已知。

e.g。

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,但据我所知,它将所有发布的值绑定到您传入的模型对象的属性。我只是想得到单个已发布参数的相应对象。

2 个答案:

答案 0 :(得分:1)

您可以使用TryUpdateModel作为rouen建议,您也可以实现可以绑定正确类型的自定义模型绑定器。这种方法的优点是可以让您处理接口或抽象模型,并使绑定代码不受您的操作影响。它有点整洁但我只是推荐它,如果它将在你的代码的其他部分重用。

答案 1 :(得分:0)

使用控制器方法 TryUpdateModel

http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.tryupdatemodel.aspx

它将根据参数类型选择合适的活页夹并为您执行模型绑定。