I have a model like this
public string Name { get; set; }
public IEnumerable<int> ProjectMembersId { get; set; }
The property Name should be bound using the standart binding code.
But the property ProjectMembersId should be bound using my custom code.
So I derived a class from the DefaultModelBinder and overrided the SetProperty method.
protected override void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, object value)
{
if (propertyDescriptor.Name == "ProjectMembersId")
{
var list = new List<int>(5);
var form = controllerContext.HttpContext.Request.Form;
var names = form.AllKeys.Where(x => x.StartsWith("dhxGridObj"));
foreach (var name in names)
{
int i;
if (int.TryParse(form.Get(name), out i))
{
list.Add(i);
}
}
value = list;
}
base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);
}
Bud the problem is the SetProperty method isn't called because the value provider doesn't contain an item called ProjectMembersId.
Maybe I'm overriding a wrong part of the defaultModelBinder. So what'd be the best way to go ?
Try it with BindProperty
method:
public class CustomModelBinder : DefaultModelBinder
{
protected override void BindProperty(ControllerContext controllerContext,
ModelBindingContext bindingContext,
System.ComponentModel.PropertyDescriptor propertyDescriptor)
{
if (propertyDescriptor.Name == "ProjectMembersId")
{
var list = new List<int>(5);
var form = controllerContext.HttpContext.Request.Form;
var names = form.AllKeys.Where(x => x.StartsWith("dhxGridObj"));
foreach (var name in names)
{
int i;
if (int.TryParse(form.Get(name), out i))
{
list.Add(i);
}
}
SetProperty(controllerContext, bindingContext, propertyDescriptor, list);
}
else
{
base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With