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.