15

我想知道是否有一种方法可以使用类似于在控制器操作之前发生的内部模型绑定的内置模型绑定。

我的问题是我希望能够控制绑定,因为在我实际处于控制器操作的上下文中之前我不会知道要绑定的对象的类型。

我知道我可以继承 DefaultModelBinder 来执行自定义绑定,但我对已经提供的东西很满意,并且只想利用它 - 以这个理想的例子来了解我所追求的:

public ActionResult DoCustomBinding(string modelType)
{
    ... // logic to determine type to check and create strong 'actual' type

    object model = BindModel(actualType);

    ... // do something with bound model

    return View();
}

我已经研究过使用 DefaultModelProvider,但不确定这是否是正确的方法,我不确定如何获取 ModelBindingContext。

4

3 回答 3

12

如果有人像我在这里所做的那样从谷歌遇到这个问题,那么答案是:如何控制模型绑定?

简而言之: TryUpdateModel 是您正在寻找的方法。

于 2012-05-31T01:42:44.233 回答
1

如果您只想验证模型的特定部分,这可能与我之前回答的问题MVC Partial Model Updates重复。

使用System.ComponentModel.DataAnnotations.MetadataType很酷的部分是模型绑定器将继续绑定到派生对象,该派生对象与基础对象基本相同,只是具有不同的显示/验证元数据。

于 2012-04-04T21:27:10.313 回答
0

您是否查看过 IModelBinder 接口?

public class CustomModelsBinder : IModelBinder {
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { }
}

然后将其添加到您的 global.asax 文件中:

protected override void OnApplicationStarted() {
   ModelBinders.Binders.Add(typeof(CustomModels), new CustomModelsBinder());
}
于 2012-04-04T20:39:18.683 回答