布爾數據類型的自定義模型綁定器如何?你需要這樣的東西:
/// <summary>
/// A custom model binder for boolean values. This behaves the same as the default
/// one, except it will resolve the value to false if it cannot be parsed.
/// </summary>
public class BooleanModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
//MVC checkboxes need specific handling in checked state
if (string.Equals(valueResult.AttemptedValue, "true,false"))
{
AddToModelState(bindingContext, valueResult);
return true;
}
bool parsed = false;
if (Boolean.TryParse(valueResult.AttemptedValue, out parsed))
{
AddToModelState(bindingContext, valueResult);
return parsed;
}
return false;
}
private static void AddToModelState(ModelBindingContext bindingContext, ValueProviderResult valueResult)
{
bindingContext.ModelState.Add(bindingContext.ModelName, new ModelState { Value = valueResult });
}
}
//in Global.asax
protected void Application_Start()
{
...
ModelBinders.Binders.Add(typeof(bool), new BooleanModelBinder());
}
這將很高興知道。希望答案不涉及編寫你自己的模型綁定。 – Gromer
這就是我所希望的,格羅默。這是一個有機的,不經常發生的錯誤,但非常煩人。 – Dusda
如何創建一個具有'photosonly'作爲字符串參數而不是bool的超載,它只是返回一個false的結果,調用正常的結果呢? – Bobson