Case Insensitive Model Binding MVC 4
Asked Answered
E

1

6

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 ?

Elainaelaine answered 24/10, 2013 at 10:7 Comment(4)
I thought the DefaultModelBinder was case-intensive already? Can you show the code where it seems case-sensitive.Maziemazlack
Actually, me too. I have no idea what I did, but it's just not the way it seems to behave now.Elainaelaine
What are you trying to do then?Maziemazlack
I have an object which first letter of properties are uppercase. I serialize it and send it to an mvc controller in an http POST. The action in the mvc controller is trying to bind it to a similar model, but with lower-case first letters. It used to work fine, but after some heavy refactoring (apparently unrelated), it doesn't. To be precise, it works on POST, but not on PUT. And still, it depends on the properties. Some are deserialized fine, others (like "idOrder") are not.Elainaelaine
E
8

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);
    }
}
Elainaelaine answered 24/10, 2013 at 12:1 Comment(1)
If your answer solved the problem you had, please accept it as the correct answer. "To be crystal clear, it is not merely OK to ask and answer your own question, it is explicitly encouraged."Ionize

© 2022 - 2024 — McMap. All rights reserved.