【问题标题】:Is there a way to short-circut data annotation based model validation?有没有办法短路基于数据注释的模型验证?
【发布时间】:2019-01-16 21:58:48
【问题描述】:

有没有办法告诉ASP.NET MVC:

  1. 在某个验证属性失败时继续验证其余验证属性?

  2. 然后,还要继续进行其余的验证属性,而不管特定属性是否失败?无论如何,这似乎是默认行为。

例如

[MaxLength(200)] // don't go ahead with the next 
                 // validation attribute applied, i.e. the
                 // RegularExpressionAttribute below if this one 
                 // fails, since there really would be no point in 
                 // doing that.
[RegularExpression(...)]
public string MyProperty { get; set; }

然后有时也以另一种方式配置它,即不告诉是短路,这似乎是目前的默认行为,如下所示:

[MaxLength(200)]  // sure, go ahead with the next one 
                  // even if this one fails
[RegularExpression(...)]
public string MyProperty { get; set; }

基本上,我的问题和this unanswered question差不多。

我正在使用面向 .NET 框架 4.5.2 的 ASP.NET MVC 5.2.7。

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-5 data-annotations


    【解决方案1】:

    简而言之,我认为 MVC 不会通过提供的数据注释来提供此功能。

    您应该问问自己为什么要遵循您提出的方法。 MVC 数据注释执行的验证类型在计算上很简单,第一次失败时存在没有意义。如果您的注释正在装饰视图模型,用户几乎肯定会更愿意看到所有失败的内容,因此他们可以一次性纠正所有错误。重新提交表单只是为了找到后续字段验证失败将是一场噩梦。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-13
      • 1970-01-01
      • 2016-07-29
      相关资源
      最近更新 更多