Custom model binding on derived property not working

房东的猫 提交于 2019-12-07 19:06:01

问题


I have a custom ModelBinder (MVC3) that isn't getting fired for some reason. Here are the relevant pieces of code:

View

@model WebApp.Models.InfoModel
@using Html.BeginForm()
{
    @Html.EditorFor(m => m.Truck)
}

EditorTemplate

@model WebApp.Models.TruckModel
@Html.EditorFor(m => m.CabSize)

ModelBinder

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

Global.asax

protected void Application_Start()
{
    ...
    ModelBinders.Binders.Add(typeof(TruckModel), new TruckModelBinder());
    ...
}

InfoModel

public class InfoModel
{
    public VehicleModel Vehicle { get; set; }
}

VehicleModel

public class VehicleModel
{
    public string Color { get; set; }
    public int NumberOfWheels { get; set; }
}

TruckModel

public class TruckModel : VehicleModel
{
    public int CabSize { get; set; }
}

Controller

public ActionResult Index(InfoModel model)
{
    // model.Vehicle is *not* of type TruckModel!
}

Why isn't my custom ModelBinder firing?


回答1:


You will have to associate the model binder with the base class:

ModelBinders.Binders.Add(typeof(VehicleModel), new TruckModelBinder());

Your POST action takes an InfoModel parameter which itself has a Vehicle property of type VehicleModel. So MVC has no knowledge of TruckModel during the binding process.

You may take a look at the following post of an example of implemeting a polymorphic model binder.



来源:https://stackoverflow.com/questions/8085541/custom-model-binding-on-derived-property-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!