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!