2010-11-01 37 views
1

我正在開發中,我有一個名爲SecurityQuestionID屬性的用戶類,如下一個ASP.NET MVC2應用:RangeAttribute數據標註工作不正常

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

的SecurityQuestionID場被從下拉填充視圖如下:

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

該控制器通過使用視圖數據如下發送的安全性問題的視圖:

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

如果我不從下拉列表中選擇一個問題,然後點擊提交按鈕,然後安全問題字段是必需的。消息顯示,而不是安全問題需要。任何人都可以幫助我瞭解我在這裏做錯了什麼?

回答

4

如果整數不爲空,則默認情況下它是必需的。因此,範圍驗證不失敗,但所需的驗證失敗。
您可能希望通過添加必需屬性來指定單獨的錯誤消息,以便何時需要它。

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

它可能會拋出該錯誤,因爲它是必填字段。見http://forums.asp.net/p/1391688/2977493.aspx。這與所涉及的字段被定義爲int而不是int?的事實一致,所以它不能假定null值。

換句話說,它沒有打到你的範圍驗證器。