[英]Extending ASP.NET MVC 2 Model Binder to work for 0, 1 booleans
我注意到在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());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.