2

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?

Jerad Rose
  • 15,235
  • 18
  • 82
  • 153

1 Answers1

7

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.

Community
  • 1
  • 1
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Perfect, makes sense now. Thanks Darin. – Jerad Rose Nov 10 '11 at 20:18
  • Quick follow up. I tried this, and it works for the most part, except my model values are all coming back default/null. I will update the code in my OP with that I have now. – Jerad Rose Nov 10 '11 at 21:13
  • Never mind, I'm going to mark this as the answer, as it resolved my original issue of the custom ModelBinder not being bound properly. I'm rolling back my edit and will create a new question on this new issue. Thanks again. – Jerad Rose Nov 10 '11 at 22:18
  • [Follow-up question](http://stackoverflow.com/questions/8087274/polymorphic-custom-model-binder-not-populating-model-w-values). – Jerad Rose Nov 10 '11 at 22:31