【问题标题】:Custom Model Binding MVC自定义模型绑定 MVC
【发布时间】:2012-08-01 10:29:39
【问题描述】:

我正在尝试将 JSON 对象列表传递给控制器​​方法,并自动在控制器中定义和填充正确的类型。

JSON 发布到控制器:

{ Type : 'Image', ImageName : 'blah.jpg' },
{ Type : 'Text', Text: 'Hello', Font: 'Some Font' }.. 

控制器:

public ActionResult SaveCOntent(IList<Item> content)

所以我得到的印象是我需要使用 ModelBinding 将元素转换为正确的类型。我已经尝试关注另一个建议的帖子(http://stackoverflow.com/questions/6484972/viewmodel-with-listbaseclass-and-editor-templates),它在某种程度上起作用..我得到了正确“类型”的列表' 但所有属性都设置为默认值且未填充。

我尝试使用以下方法扩展 DefaultModelBinder:

public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var typeName = (string)bindingContext.ValueProvider.GetValue(bindingContext.ModelName + ".ItemTypeName").ConvertTo(typeof(string));

        if (typeName == "LINK")
        {

            bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => new Link(), typeof(Link));

            base.BindModel(controllerContext, bindingContext);
        }
        else if (typeName == "IMAGE")
        {
            //bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => new Image(), typeof(Image));
            //base.BindModel(controllerContext, bindingContext);
            return null;

        }

        return base.BindModel(controllerContext, bindingContext);
    }

现在这适用于第一种类型(链接),但是一旦我尝试对 Image 执行相同操作,我就会收到一条错误提示

已添加具有相同密钥的项目。

【问题讨论】:

  • 我发现是什么导致了相同的键错误,基本上在不同的继承级别有两个具有相同名称的属性.. 仍然想知道是否有更好的方法来做到这一点?跨度>

标签: asp.net-mvc json deserialization model-binding


【解决方案1】:

原来它工作正常,我的问题是这个对象的基类有一个同名的属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-27
    • 2015-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多