[英]Polymorphic custom model binder not populating model w/ values
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: 例如,在我的视图(EditorTemplate)中,我具有:
@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. 将typeValue
和type
变量设置为适当的值(类型为TruckModel
),但是在执行GetMetadataForType
,仍然使用空值/默认值填充model
。
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. 您可以通过参考我之前关于该主题的文章找到有关视图/模型设置的更多详细信息。
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. 正如@sydneyos在上面的注释中所述,我的模型实际上已被填充,但是显然在CreateModel方法中,返回的模型将不包含该点的值。
In my case, I was getting an ArgumentNullException
following this method, which I thought was due to the model not getting populated. 就我而言,在此方法之后,我收到了ArgumentNullException
,我认为是由于未填充模型。 But turns out, it was unrelated, and once this was fixed, the model binding worked as expected. 但是事实证明,这是不相关的,并且一旦解决了这个问题,模型绑定就会按预期工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.