Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net mvc 3 - Custom model binding

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 ?

like image 784
user256034 Avatar asked Jan 21 '23 07:01

user256034


1 Answers

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);
            }
        }
    }
like image 132
frennky Avatar answered Jan 30 '23 20:01

frennky