MVC3 DataAnnotationsExtensions error using numeric

2019-03-31 01:56发布

I've installed Scott's Kirkland DataAnnotationsExtensions.

In my model I have:

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

And in my View:

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

Now, when the page tries to render I get the following error:

Validation type names in unobtrusive client validation rules must be unique. The following validation type was seen more than once: number

Any ideas why I'm getting the error ?

2条回答
爷、活的狠高调
2楼-- · 2019-03-31 02:28

The quick answer is simply remove the attribute

[Numeric]

The longer explanation is that by design, validation already adds a data-val-number because it's of type double. By adding a Numeric you are duplicating the validation.

this works:

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

because the variable is of type string and you are adding the Numeric attribute.

Hope this helps

查看更多
混吃等死
3楼-- · 2019-03-31 02:47

I basically had the same problem and I managed to solve it with the following piece of code: (As answered here: ASP.NET MVC - "Validation type names must be unique.")

using System; using System.Web.Mvc; And the ValidationRule:

public class 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);
}

}

I hope this helps.

查看更多
登录 后发表回答