自定义模型绑定MVC [英] Custom Model Binding MVC

查看:70
本文介绍了自定义模型绑定MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想传递一个列表的JSON对象到控制器的方法,并自动具有正确的类型定义并在控制器填充。

I'm trying to pass a list of JSON objects to a controller method, and automatically have the correct types defined and populated in the controller.

JSON发布到控制器:

JSON Posted to controller:

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

控制器:

public ActionResult SaveCOntent(IList<Item> content)

因此​​,IM pression我得的是,我需要用ModelBinding的元素转换为正确的类型。我尝试以下建议的另一个职位(http://stackoverflow.com/questions/6484972/viewmodel-with-listbaseclass-and-editor-templates),这在某种程度上工程..我得到正确的'类型的列表但所有的属性都设置为默认值,而不是填充。

So the impression i've got is that I need to use ModelBinding to convert the elements into the correct type. I've tried following another suggested post (http://stackoverflow.com/questions/6484972/viewmodel-with-listbaseclass-and-editor-templates), which works in a way.. I get a list of the correct 'types' but all the properties are set to defaults and not populated.

我试图扩大与下面的DefaultModelBinder:

I've tried extending the DefaultModelBinder with the following:

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

现在这工作正常的第一类(链接),但只要我尝试的图像做同样的我得到一个错误,说明

Now this works fine for the first type (Link), but as soon as I try to do the same for Image I get an error stating

具有相同键的项已被添加。

An item with the same key has already been added.

推荐答案

横空出世,它工作正常,我的问题是与基类具有相同名称的属性此对象。

Turned out it works fine and my issue was with the base class of this object having a property with the same name.

这篇关于自定义模型绑定MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆