这不是“必需”问题,它是基本的 ModelBinding 组件:不可为空的类型在 DefaultModelBinder 中不能为空。如果 ModelBinding 失败,Model.IsValid = false => 显示此类错误。
bool?(可以为空)或string(相同)不会出现“错误”消息,但bool(不是)会出现“错误”消息。
(这是基本的“强类型逻辑”:尝试在 c# 中编写 DateTime dt = null...)
因此,一种解决方案可能是创建一个新的 ModelBinder(例如,所有“null”布尔值都设置为 false)。 但我真的不确定这是否是您所需要的。默认行为通常很好
我只是给你一个 CustomModelBinder 的例子:我们使用它来避免在我们的大多数数字字段中键入 0 值:当没有在具有 Int32、UInt32 和双值的字段中键入值时,它的值设置为 0
public class AcceptNullAsZeroModelBinder : DefaultModelBinder
{
protected override void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, object value)
{
if (value == null && (
propertyDescriptor.PropertyType == typeof(Int32) ||
propertyDescriptor.PropertyType == typeof(UInt32) ||
propertyDescriptor.PropertyType == typeof(double)
))
{
base.SetProperty(controllerContext, bindingContext, propertyDescriptor, 0);
return;
}
base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);
}
}