我有一个整数?查看在客户端验证的模型属性,就好像它是必需的一样。也就是说,如果我将该字段留空,它将不会提交。字符串属性不会发生同样的情况。
为我的编辑器呈现的 HTML 是:
<input type="text" value="" name="StatusIdSearch" id="StatusIdSearch" data-val-number="The field Status must be a number." data-val="true" class="text-box single-line">
我认为 data-val-number
导致错误,因为没有什么不是数字,但我无法确定原因。
有什么想法吗?
编辑
View 模型:
public class CompromissoSearchModel
{
// other properties removed for the sake of clarity
[Display(Name = "Status")]
[EnumDataType(typeof(StatusCompromisso))]
public int? StatusIdSearch { get; set; }
// other properties removed for the sake of clarity
}
最佳答案
您看到的消息与必填字段验证无关。你得到这个是因为 ClientDataTypeModelValidatorProvider
添加客户端数字验证,它会忽略类型是否可为空。你可以check the code yourself :
private static IEnumerable<ModelValidator> GetValidatorsImpl(
ModelMetadata metadata,
ControllerContext context)
{
Type type = metadata.RealModelType;
if (IsNumericType(type)) {
yield return new NumericModelValidator(metadata, context);
}
}
IsNumericType
实现:
private static bool IsNumericType(Type type)
{
// strip off the Nullable<>
Type underlyingType = Nullable.GetUnderlyingType(type);
return _numericTypes.Contains(underlyingType ?? type);
}
由于不考虑可为 nullable,因此您总是会得到该验证。在解决方案方面,您需要从使用的提供程序中删除 ClientDataTypeModelValidatorProvider
,或者用不忽略 nullable 的自定义提供程序替换它。
关于c# - 为什么我的是int?是否需要验证值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9084709/