扩展ASP.NET MVC 2模型绑定为0,1布尔工作 [英] Extending ASP.NET MVC 2 Model Binder to work for 0, 1 booleans

查看:72
本文介绍了扩展ASP.NET MVC 2模型绑定为0,1布尔工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我和ASP.NET MVC 2注意到,模型绑定将无法识别1和0真正分别。是否有可能延长模型绑定的全球可认识到这些,并把它们变成相应的布尔值?

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?

谢谢!

推荐答案

在电线之间的事情应该做的工作:

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

和在注册的Application_Start

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

这篇关于扩展ASP.NET MVC 2模型绑定为0,1布尔工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆