I've searched high and low so hopefully someone can help me. I have a class:
public class Person
{
public string Name { get; set; }
public ICollection<Toys> { get; set; }
}
I have a controller method:
public ActionResult Update(Person toycollector)
{
....
}
I want to bind to the collection. I realize I will only get the IDs but I will deal with that in my controller. I just need to be able to flip through the collection of IDs. I started writing a model binder:
public class CustomModelBinder : DefaultModelBinder
{
protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
{
if (propertyDescriptor.PropertyType == typeof(ICollection<Toys>))
{
//What do I do here???
}
}
So how do I build the collection of Toys from the values passed into my method? Thanks!
EDIT: Looks like I couldn't post this answer to my own question so I'll just edit my post. looks like all you have to do is parse out the data and add it to the model like so:
if (propertyDescriptor.PropertyType == typeof(ICollection)) {
var incomingData = bindingContext.ValueProvider.GetValue("Edit." + propertyDescriptor.Name + "[]");
if (incomingData != null)
{
ICollection<Toy> toys = new List<Toy>();
string[] ids = incomingData.AttemptedValue.Split(',');
foreach (string id in ids)
{
int toyId = int.Parse(id);
toys.Add(new Toy() { ToyID = toyId });
}
var model = bindingContext.Model as Person;
model.Toys = toys;
}
return;
}