c# - 为什么我的是int?是否需要验证值?

标签 c# asp.net asp.net-mvc-3 jquery-validate

我有一个整数?查看在客户端验证的模型属性,就好像它是必需的一样。也就是说,如果我将该字段留空,它将不会提交。字符串属性不会发生同样的情况。

为我的编辑器呈现的 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/

相关文章:

javascript - 部分回发后脚本无法正常工作

asp.net-mvc - MVC 返回 Json 结果

asp.net-mvc-3 - ASP.NET Web API Ninject 构造函数注入(inject)自定义过滤器和属性

c# - 如何判断Task.Run是否在一个循环内完成

c# - 适用于 .net 的 Foursquare SDK

c# - 数据从 DAL 传输到 MVC View

c# - <select> 标记多个属性使用 runat=server | 引发解析器错误类型为 'System.Boolean' 的对象

asp.net - jQuery-AJAX 调用 ASP.NET 页面方法。如何将值返回给 jQuery?

javascript - 使用与 MVC PartialViewResult 签名匹配的对象动态填充 Ajax 数据属性

asp.net - 在执行大型操作时向 View 发送更新的策略