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 ?

tereško
  • 58,060
  • 25
  • 98
  • 150
Romain Vergnory
  • 1,496
  • 15
  • 30
  • 3
    I thought the `DefaultModelBinder` was case-intensive already? Can you show the code where it seems case-sensitive. – Henk Mollema Oct 24 '13 at 10:30
  • Actually, me too. I have no idea what I did, but it's just not the way it seems to behave now. – Romain Vergnory Oct 24 '13 at 12:04
  • What are you trying to do then? – Henk Mollema Oct 24 '13 at 12:18
  • 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. – Romain Vergnory Oct 24 '13 at 12:26

1 Answers1

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);
    }
}
JLRishe
  • 99,490
  • 19
  • 131
  • 169
Romain Vergnory
  • 1,496
  • 15
  • 30
  • 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."](http://blog.stackoverflow.com/2011/07/its-ok-to-ask-and-answer-your-own-questions/) – Oliver Feb 21 '14 at 10:50