MVC3 validation with data-annotation?

只愿长相守 提交于 2019-12-21 23:24:14

问题


Is it possible to use a data-annotation attribute for dropdownlists to be valid, only if the user selects an option different from one with the value o (zero). The option with value o (zero) is "Please Select an account", which is selected by default. I used [Required] attribute to validate this dropdownlist, but it doesn't have any effect, because, how I said, by default the option with value o (zero)- "Please Select an account"- is selected.


回答1:


Something like:

[Range(1, int.MaxValue, ErrorMessage = "Please enter a value bigger than {1}")]
public int Value { get; set; }



回答2:


Making a drop-down list required does not make sense. What you want required is that the user pick a value other than zero from the drop-down list. So what should be required is the SelectedAccount property. You should use the MVC helper method to bind the drop-down selected value to the SelectedAccount property:

@Html.DropdownListFor(m => m.SelectedAccount, new SelectList(Model.Accounts))

I am probably off on the syntax but you can look that up.

Now with regards to your other issue of ensuring that the value is not zero. Is the account number represented as a number or can it contain non-numeric characters? If it is a number then you should represent it as such in your code. And if it is truly a string, then the first value of your drop-down list should be an empty string and not zero.

If you decide that it is a number, then use the Range annotation to ensure that the value is greater than zero:

[Required]
[Range(1, Int32.MaxValue)]
public string SelectedAccountNumber {get;set;} 

Hope that helps!



来源:https://stackoverflow.com/questions/12530648/mvc3-validation-with-data-annotation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!