开发者

RangeAttribute Data Annotation Not Working as Expected

I am developing an ASP.NET MVC2 application in which I have a User class with a property named SecurityQuestionID as follows:

public class User
{
    [RangeAttribute(1, 5, ErrorMessage = "Security Question is required")]
    [DisplayName("Security Question")]开发者_开发百科
    public virtual int SecurityQuestionID { get; set; }
}

The SecurityQuestionID field gets populated from a dropdown in the view as follows:

<%: Html.LabelFor(model => model.SecurityQuestionID)%>
<%: Html.DropDownListFor(model => model.SecurityQuestionID, ViewData["securityQuestions"] as SelectList,"Choose a Question",null) %>
<%: Html.ValidationMessageFor(model => model.SecurityQuestionID)%>

The controller sends the security questions to the view by using view data as follows:

ViewData["securityQuestions"] = new SelectList(_securityQuestionService.GetAll(), "SecurityQuestionID", "Question");

If I don't select a question from the dropdown and hit the submit button, then "The Security Question field is required." message is displayed instead of "Security Question is required". Can anyone help me understand what I am doing wrong here?


If the integer is not nullable, then it is required by default. So the range validation isn't failing but Required validation is failing.
You may want to specify a separate error message for when it is required by adding a required attribute.

[Required(ErrorMessage="Security Question is required")]


It's probably throwing that error because it is a required field. See http://forums.asp.net/p/1391688/2977493.aspx. This is consistent with the fact that the field in question is defined as an int, and not an int?, so it cannot assume a null value.

In other words, it's not hitting your range validator.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜