6

モデル バインディングで大文字と小文字を区別しないようにしたいと考えています。

から継承するカスタム モデル バインダーを操作しようとしSystem.web.Mvc.DefaultModelBinderましたが、大文字と小文字を区別しないように追加する場所がわかりません。

も見ましたIValueProviderが、車輪を再発明して値を自分で見つけたくありません。

何か案が ?

4

1 に答える 1

8

を持つこと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);
    }
}
于 2013-10-24T12:01:52.167 に答える