Case Insensitive Model Binding MVC 4

时间:2013-10-24 10:07:31

标签: asp.net-mvc asp.net-mvc-4 model-binding custom-model-binder value-provider

我希望我的模型绑定不区分大小写。

我尝试操作继承自System.web.Mvc.DefaultModelBinder的自定义模型绑定器,但我无法弄清楚在何处添加不区分大小写。

我还看了一下IValueProvider,但我不想重新发明轮子并自己找到价值观。

有什么想法吗?

1 个答案:

答案 0 :(得分:4)

拥有CustomModelBinder是解决方案。因为我不需要完全不区分大小写,所以我只检查是否找到了我的属性的小写版本。

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);
    }
}
相关问题