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

醉酒当歌 提交于 2019-12-18 04:09:13

问题


I've noticed with ASP.NET MVC 2 that the model binder will not recognize "1" and "0" as true and false respectively. Is it possible to extend the model binder globally to recognize these and turn them into the appropriate boolean values?

Thanks!


回答1:


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());



回答2:


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());


来源:https://stackoverflow.com/questions/4786591/extending-asp-net-mvc-2-model-binder-to-work-for-0-1-booleans

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