【问题标题】:Why is my int? value being validated as if it was required?为什么是我的int?是否需要验证值?
【发布时间】:2012-01-31 18:13:01
【问题描述】:

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

为我的编辑器呈现的 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 导致错误,因为没有什么不是数字,但我无法确定原因。

有什么想法吗?

编辑

视图模型:

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
}

【问题讨论】:

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


【解决方案1】:

您看到的消息与必填字段验证无关。你得到这个是因为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);
}

由于不考虑可空值,因此您始终会获得该验证。在解决方案方面,您需要从使用的提供者中删除ClientDataTypeModelValidatorProvider,或者将其替换为不忽略可空值的自定义提供者。

【讨论】:

  • angelo:我还在分析你的答案。这很奇怪,因为我刚刚创建了一个新的 MVC 项目和 int?属性未按要求验证,而 [Required] 属性是。这个特定项目有些奇怪,因为它似乎不是预期的行为。
【解决方案2】:

您应该能够将以下代码添加到 Global.asax 文件中的 Application_Start 方法以解决此问题:

DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;

【讨论】:

  • 谢谢 Scott,但这将导致不可为空的值类型接受来自客户端的空值
  • 我发现可空值类型的这种行为反直觉。
【解决方案3】:

我遇到了完全相同的问题并设法找到了解决方案。这些解决方案都不适合我,所以我想我会将我的解决方案发布给遇到此问题的其他人。

问题不在于模型绑定器将字段验证为无效,而是在使用 TryUpdateModel 时,视图模型的可为空属性在数据库实体中不可为空。

更清晰的解释:

TryUpdateModel(dbUser, "", new[]{
    "DecimalProperty"
}));

视图模型中的“DecimalProperty”可以为空,但在 dbUser 中不能为空。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-11
    • 1970-01-01
    • 1970-01-01
    • 2017-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-08
    相关资源
    最近更新 更多