Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 483
jocull Avatar asked Feb 03 '23 22:02

jocull


1 Answers

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());
like image 75
Darin Dimitrov Avatar answered Feb 05 '23 11:02

Darin Dimitrov