I would like to bind a dropdownlist to an integer as follows:
@Html.DropDownListFor(m => m.ProductID, Model.AllProducts, "")
Obviously in the above case I am allowing for a default (blank) value so that no value is chosen by default. My viewmodel is very simple, and doesn't have any annotations for these properties
public SelectList AllProducts {get;set;}
public int ProductID {get;set;}
It appears that because I am binding to an int data validation is forced resulting in data-val* attributes generated in my html and causing my client side validation to fail if i do not choose an option. The alternative seems to be binding to a string rather than an int and then parsing the string on the serverside - however, this seems kind of hackish and i'm wondering if there is an alternative that would allow me to bind to an int, with a default (empty) value but not make this field mandatory
Thank you
JP
You should use a nullable integer in in your view model to bind to if the drop down ilst could have a default value:
public SelectList AllProducts { get; set; }
public int? ProductID { get; set; }
And if you want to enforce validation that the user actually selects a value decorate with the Required attribute:
public SelectList AllProducts { get; set; }
[Required]
public int? ProductID { get; set; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With