Reputation: 2312
I have the following classes:
public class Movie
{
string Name get; set;
string Director get; set;
IList<Tag> Tags get; set;
}
public class Tag
{
string TagName get; set;
}
On the Action of my controller I bind like this: public ActionResult Create([ModelBinder(typeof(MovieBinder))]Movie mo)
on theMovieBinder I convert the string to List<tag>
. That when I debug works.
on the Movie binder I have the following code:
if (propertyDescriptor.Name == "Tags")
{
var values = bindingContext.ValueProvider.GetValue(propertyDescriptor.Name);
if (values != null)
{
var p = values.AttemptedValue.Replace(" ", "");
var arrayValues = p.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
var list = new List<Tag>();
foreach (string item in arrayValues)
{
list.Add(new Tag() { TagName = item });
}
value = list;
}
}
But I get the following Error in the modelstate: Exception = {"The parameter conversion from type 'System.String' to type 'Models.Tag' failed because no type converter can convert between these types."}
I create a Tag binder, but it does not work, any ideas? Thanks!
Upvotes: 0
Views: 353
Reputation: 1039598
You could adapt the model binder I suggested here to this new situation where you have introduced the Tag
class:
public class MovieModelBinder : DefaultModelBinder
{
protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder)
{
if (propertyDescriptor.Name == "Tags")
{
var values = bindingContext.ValueProvider.GetValue(propertyDescriptor.Name);
if (values != null)
{
return values.AttemptedValue.Split(',').Select(x => new Tag
{
TagName = x
}).ToList();
}
}
return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder);
}
}
Upvotes: 1