Extending ASP.NET MVC 2 Model Binder to work for 0, 1 booleans

柔情痞子 提交于 2019-11-29 04:07:06

Something among the lines should do the job:

public class BBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        if (value != null)
        {
            if (value.AttemptedValue == "1")
            {
                return true;
            }
            else if (value.AttemptedValue == "0")
            {
                return false;
            }
        }
        return base.BindModel(controllerContext, bindingContext);
    }
}

and register in Application_Start:

ModelBinders.Binders.Add(typeof(bool), new BBinder());

Check out this link. It apparently works in MVC2.

You could do something like (untested):

public class BooleanModelBinder : IModelBinder {
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
        ValueProviderResult value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        // do checks here to parse boolean
        return (bool)value.AttemptedValue;
    }
}

Then in the global.asax on application start add:

ModelBinders.Binders.Add(typeof(bool), new BooleanModelBinder());
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!