我注意到 ASP.NET MVC 2 模型绑定(bind)器不会将“1”和“0”分别识别为 true
和 false
。是否可以全局扩展模型绑定(bind)器以识别这些并将它们转换为适当的 bool 值?
谢谢!
最佳答案
行中的某些内容应该可以完成这项工作:
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());
关于c# - 扩展 ASP.NET MVC 2 模型绑定(bind)器以适用于 0、1 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4786591/