我希望我的模型绑定(bind)不区分大小写。
我尝试操作从 System.web.Mvc.DefaultModelBinder
继承的自定义模型绑定(bind)器,但我不知道在哪里添加不区分大小写。
我还看了IValueProvider
,但我不想重新发明轮子并自己找到值(value)观。
任何的想法 ?
最佳答案
拥有 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);
}
}
关于asp.net-mvc - 不区分大小写的模型绑定(bind) MVC 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19562950/