Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case Insensitive Model Binding MVC 4

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 ?

like image 623
Romain Vergnory Avatar asked Oct 24 '13 10:10

Romain Vergnory


1 Answers

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);
    }
}
like image 133
Romain Vergnory Avatar answered Sep 21 '22 23:09

Romain Vergnory