扩展ASP.NET MVC 2 Model Binder以适用于0,1个布尔值

joc*_*ull 9 c# asp.net-mvc-2

我注意到在ASP.NET MVC 2,该模型粘结剂将无法识别"1"和"0" truefalse分别.是否可以全局扩展模型绑定器以识别它们并将它们转换为适当的布尔值?

谢谢!

Dar*_*rov 9

行之间应该做的事情:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

并注册Application_Start:

ModelBinders.Binders.Add(typeof(bool), new BBinder());
Run Code Online (Sandbox Code Playgroud)