简体   繁体   中英

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM