问题
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.
回答1:
Turned out it works fine and my issue was with the base class of this object having a property with the same name.
来源:https://stackoverflow.com/questions/11757322/custom-model-binding-mvc