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?
Darin Dimitrov
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