1

I have a custom model binder that I'm using to return the appropriate model sub-type based on a hidden value containing the original type.

For example, in my view (EditorTemplate) I have:

@model MyWebApp.Models.TruckModel
@Html.Hidden("ModelType", Model.GetType())
@Html.EditorFor(m => m.CabSize)

Then, in my custom model binder, I have:

    protected override object CreateModel(ControllerContext controllerContext, 
        ModelBindingContext bindingContext, Type modelType)
    {
        var typeValue = bindingContext.ValueProvider
            .GetValue(bindingContext.ModelName + ".ModelType");

        var type = Type.GetType((string)typeValue.ConvertTo(typeof(string)), true);

        var model = Activator.CreateInstance(type);

        bindingContext.ModelMetadata = ModelMetadataProviders.Current
            .GetMetadataForType(() => model, type);

        return model;
    }

The typeValue and type variables are getting set to the appropriate values (type is TruckModel), but after doing GetMetadataForType, model is still populated with null/default values.

I checked out several posts (here and here to name a couple), and it seems like I'm doing everything as explained here, but it's still not working for me.

You can find more details on the view/model setup by referring to my previous post on this topic.

Community
  • 1
  • 1
Jerad Rose
  • 15,235
  • 18
  • 82
  • 153
  • 1
    I think you would expect default values at this stage - it's only after the calls to GetPropertyValue that the model will actually be populated with values from the view - have you stepped through that method? – sydneyos Nov 11 '11 at 05:58
  • @sydneyos - You are right, the values aren't supposed to be getting set at this point. I was never able to see this due to an exception getting thrown before it made it to my controller (an unrelated exception `ArgumentNullException`, but I thought was related). Once I fixed this issue, it made it to my controller, and as you said, my model was populated at this point. If you can post this as an answer, I will accept it. Thanks. – Jerad Rose Nov 11 '11 at 14:41

1 Answers1

0

As @sydneyos states above in the comments, my model was actually getting populated, but apparently in the CreateModel method, the returned model will not contain the values at that point.

In my case, I was getting an ArgumentNullException following this method, which I thought was due to the model not getting populated. But turns out, it was unrelated, and once this was fixed, the model binding worked as expected.

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