Question

I would like my model binding to be case insensitive.

I tried manipulating a custom model binder inheriting from System.web.Mvc.DefaultModelBinder, but I can't figure out where to add case insensitivity.

I also took a look at IValueProvider, but I don't want to reinvent the wheel and find by myself the values.

Any idea ?

Was it helpful?

Solution

Having a CustomModelBinder was the solution. As i didn't need complete case insensitivity, I only check if the lowercase version of my property is found.

public class CustomModelBinder : DefaultModelBinder
{
    protected override void SetProperty(ControllerContext controllerContext, 
                                        ModelBindingContext bindingContext, 
                                        PropertyDescriptor propertyDescriptor, 
                                        object value)
    {
        //only needed if the case was different, in which case value == null
        if (value == null)
        {
            // this does not completely solve the problem, 
            // but was sufficient in my case
            value = bindingContext.ValueProvider.GetValue(
                        bindingContext.ModelName + propertyDescriptor.Name.ToLower());
            var vpr = value as ValueProviderResult;
            if (vpr != null)
            {
                value = vpr.ConvertTo(propertyDescriptor.PropertyType);
            }
        }
        base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top