扩展ASP.NET MVC 2 Model Binder以适用于0,1个布尔值
我注意到ASP.NET MVC 2中模型绑定器不会将“1”和“0”分别识别为true
和false
。 是否可以全局扩展模型绑定器以识别它们并将它们转换为适当的布尔值?
谢谢!
行之间应该做的事情:
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());
- 在asp.net MVC2中将html表导出为excel
- ASP.NET MVC Url.Action和路由名称值
- 在为ASP.NET MVC 2.0应用程序注册区域时提供或过滤程序集
- 如何从asp.net mvc 2应用程序中的自定义ValidationAttribute内部访问其他属性值?
- 使用控制器动作filter捕获HTML输出
- 派生的RequiredAttribute不起作用
- 需要帮助了解Ninject如何将Nhibernate SessionFactory实例添加到UnitOfWork中?
- entity frameworkCTP4:在哪里放置SetInitializer?
- 找不到文件时处理FileContentResult