Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC3 - Binding DropdownList to int - Value always required

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

like image 703
JP. Avatar asked Sep 27 '11 15:09

JP.


1 Answers

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; }
like image 111
Darin Dimitrov Avatar answered Oct 12 '22 22:10

Darin Dimitrov