多态自定义模型绑定器未填充带有值的模型
我有一个自定义模型绑定器,用于根据包含原始类型的隐藏值返回适当的模型子类型。
例如,在我的视图 (EditorTemplate) 中,我有:
@model MyWebApp.Models.TruckModel
@Html.Hidden("ModelType", Model.GetType())
@Html.EditorFor(m => m.CabSize)
然后,在我的自定义模型绑定程序中,我有:
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;
}
typeValue
和 type
变量被设置为适当的值(类型为 TruckModel
),但在执行 GetMetadataForType
后,model
仍填充有 null/默认值。
我查看了几篇文章(此处和此处举几个例子),以及似乎我正在按照此处解释的方式执行所有操作,但它仍然对我不起作用。
您可以参考我的 上一篇,找到有关视图/模型设置的更多详细信息关于此主题的帖子。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如 @sydneyos 在上面的评论中所述,我的模型实际上已被填充,但显然在 CreateModel 方法中,返回的模型将不包含此时的值。
就我而言,我在使用此方法后收到了
ArgumentNullException
,我认为这是由于模型未填充所致。但事实证明,这是不相关的,一旦修复了这个问题,模型绑定就会按预期工作。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.