【问题标题】:MVC3 DataAnnotationsExtensions error using numeric attribute使用数字属性的 MVC3 DataAnnotationsExtensions 错误
【发布时间】:2025-12-13 07:15:01
【问题描述】:

我已经安装了 Scott 的 Kirkland DataAnnotationsExtensions。

在我的模型中,我有:

[Numeric]
public double expectedcost { get; set; }

在我看来:

@Html.EditorFor(model => model.expectedcost)

现在,当页面尝试呈现时,我收到以下错误:

不显眼的验证类型名称 客户端验证规则必须是 独特。以下验证类型 不止一次被看到:数字

任何想法为什么我收到错误?

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 data-annotations unobtrusive-javascript


    【解决方案1】:

    快速的答案是简单地删除属性

    [Numeric]
    

    更长的解释是,根据设计,验证已经添加了一个 data-val-number,因为它的类型是 double。通过添加 数字,您正在复制验证。

    这行得通:

    [Numeric]
    public string expectedcost { get; set; }
    

    因为变量的类型是 string 并且您要添加 Numeric 属性。

    希望对你有帮助

    【讨论】:

      【解决方案2】:

      我基本上遇到了同样的问题,我设法用以下代码解决了它:(在这里回答:ASP.NET MVC - "Validation type names must be unique."

      使用系统; 使用 System.Web.Mvc; 还有 ValidationRule:

      公共类RequiredIfValidationRule:ModelClientValidationRule { private const string Chars = "abcdefghijklmnopqrstuvwxyz";

      public RequiredIfValidationRule(string errorMessage, string reqVal,
          string otherProperties, string otherValues, int count)
      {
          var c = "";
          if (count > 0)
          {
              var p = 0;
              while (count / Math.Pow(Chars.Length, p) > Chars.Length)
                  p++;
      
              while (p > 0)
              {
                  var i = (int)(count / Math.Pow(Chars.Length, p));
                  c += Chars[Math.Max(i, 1) - 1];
                  count = count - (int)(i * Math.Pow(Chars.Length, p));
                  p--;
              }
              var ip = Math.Max(Math.Min((count) % Chars.Length, Chars.Length - 1), 0);
              c += Chars[ip];
          }
      
          ErrorMessage = errorMessage;
          // The following line is where i used the unique part of the name
          //   that was generated above.
          ValidationType = "requiredif"+c;
          ValidationParameters.Add("reqval", reqVal);
          ValidationParameters.Add("others", otherProperties);
          ValidationParameters.Add("values", otherValues);
      }
      

      }

      我希望这会有所帮助。

      【讨论】:

      • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接的答案可能会失效。