多态自定义模型粘合剂不填充模式瓦特

多态自定义模型粘合剂不填充模式瓦特

本文介绍了多态自定义模型粘合剂不填充模式瓦特/值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我使用返回基于包含原始类型隐藏的价值适当的模型分型自定义模型粘合剂。

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.

例如,在我看来(EditorTemplate)我有:

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;
    }

typeValue 键入变量越来越设置为适当的值(类型为 TruckModel ),但这样做后 GetMetadataForType 模式仍填充空/默认值

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.

我检查了几个职位(和here命名一对夫妇),而且好像我做的一切,在这里解释,但它仍然不是为我工作。

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.

您可以参考我的$p$pvious帖子这个话题。

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

推荐答案

由于@sydneyos在评论上述规定,我的模型实际上是越来越稀少,但显然在CreateModel方法,返回的模型将不包含在该值点。

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.

在我的情况,我得到了一个 ArgumentNullException 下面这个方法,我认为是由于该模型没有得到填充。但事实证明,这是不相关的,并且,一旦这是固定的,模型绑定工作正常。

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.

这篇关于多态自定义模型粘合剂不填充模式瓦特/值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 07:03