Polymorphic custom model binder not populating mod

2020-07-27 05:28发布

问题:

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.

回答1:

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.