0

我有一个模型,我想在表单中使用EditorForModel(). 对于所有非字符串数据类型(如 bool、DateTime 等),即使我没有设置[Required}数据注释,创建的表单也会使字段成为必填字段。如何设置Object.cshtml文件以识别这不是必填字段?

4

1 回答 1

1

这不是“必需”问题,它是基本的 ModelBinding 组件:不可为空的类型在 DefaultModelBinder 中不能为空。如果 ModelBinding 失败,Model.IsValid = false => 显示此类错误。

您不会收到带有 a bool?(可以为空)或带有 a string(相同)的“错误”消息,但您会收到带有 a (不是)的“错误”消息bool

(这是基本的“强类型逻辑”:尝试用DateTime dt = nullc# 编写...)

因此,一种解决方案可能是创建一个新的 ModelBinder(例如,所有“null”布尔值都设置为 false)。但我真的不确定这是你需要的。默认行为通常很好

我只是给你一个 CustomModelBinder 的例子:我们使用它来避免在我们的大多数数字字段中键入 0 值:当没有在具有 Int32、UInt32 和 double 值的字段中键入任何值时,它将值设置为 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);
        }
    }
于 2012-05-10T22:48:36.800 回答