派生属性上的自定义模型绑定不起作用

Jer*_*ose 2 c# asp.net-mvc model-binding asp.net-mvc-3

我有一个自定义的ModelBinder(MVC3),由于某种原因没有被解雇.以下是相关的代码:

视图

@model WebApp.Models.InfoModel
@using Html.BeginForm()
{
    @Html.EditorFor(m => m.Truck)
}
Run Code Online (Sandbox Code Playgroud)

EditorTemplate

@model WebApp.Models.TruckModel
@Html.EditorFor(m => m.CabSize)
Run Code Online (Sandbox Code Playgroud)

ModelBinder的

public class TruckModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        throw new NotImplementedException();
    }
}
Run Code Online (Sandbox Code Playgroud)

Global.asax中

protected void Application_Start()
{
    ...
    ModelBinders.Binders.Add(typeof(TruckModel), new TruckModelBinder());
    ...
}
Run Code Online (Sandbox Code Playgroud)

InfoModel

public class InfoModel
{
    public VehicleModel Vehicle { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

VehicleModel

public class VehicleModel
{
    public string Color { get; set; }
    public int NumberOfWheels { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

TruckModel

public class TruckModel : VehicleModel
{
    public int CabSize { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

调节器

public ActionResult Index(InfoModel model)
{
    // model.Vehicle is *not* of type TruckModel!
}
Run Code Online (Sandbox Code Playgroud)

为什么我的自定义ModelBinder不能解雇?

Dar*_*rov 7

您必须将模型绑定器与基类关联:

ModelBinders.Binders.Add(typeof(VehicleModel), new TruckModelBinder());
Run Code Online (Sandbox Code Playgroud)

您的POST操作采用InfoModel参数,该参数本身具有VehicleModel类型的Vehicle属性.因此,MVC在绑定过程中不了解TruckModel.

您可以看一下实现多态模型绑定器的示例的以下帖子.