1

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 Posted to controller:

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

The Controller:

public ActionResult SaveCOntent(IList<Item> content)

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.

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.

tereško
  • 58,060
  • 25
  • 98
  • 150
BenW
  • 1,312
  • 10
  • 18
  • I found out what was causing the same key error, basically had two properties with the same Name at different levels of the inheritance.. Still wonder if there is a better way of doing this though? – BenW Aug 02 '12 at 12:38

1 Answers1

1

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

BenW
  • 1,312
  • 10
  • 18