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

我注意到ASP.NET MVC 2中模型绑定器不会将“1”和“0”分别识别为truefalse 。 是否可以全局扩展模型绑定器以识别它们并将它们转换为适当的布尔值?

谢谢!

行之间应该做的事情:

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

看看这个链接 。 它显然适用于MVC2。

你可以做一些像(未经测试的):

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

然后在global.asax上的应用程序开始添加:

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