Phi*_*per 15 c# asp.net-mvc model-binding
我想知道是否有一种方法可以使用类似于在控制器操作之前发生的内部模型绑定的内置模型绑定.
我的问题是我希望能够控制绑定,因为我不知道要绑定的对象的类型,直到我实际上在控制器操作的上下文中.
我知道我可以继承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();
}
Run Code Online (Sandbox Code Playgroud)
我已经研究过使用DefaultModelProvider,但不确定这是否是正确的方法,我不知道如何获取ModelBindingContext.
您研究过 IModelBinder 接口吗?
public class CustomModelsBinder : IModelBinder {
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { }
}
Run Code Online (Sandbox Code Playgroud)
然后将其添加到您的 global.asax 文件中:
protected override void OnApplicationStarted() {
ModelBinders.Binders.Add(typeof(CustomModels), new CustomModelsBinder());
}
Run Code Online (Sandbox Code Playgroud)