MVC3 - binding DropdownList to int - value is always required

I would like to associate a dropdown with an integer as follows:

@Html.DropDownListFor(m => m.ProductID, Model.AllProducts, "")

Obviously, in the case above, I am assuming a default value (empty) so that the default value is not selected. My view model is very simple and does not contain annotations for these properties.

public SelectList AllProducts {get;set;}
public int ProductID {get;set;}

It seems that since I am attached to validating int data, it forces the appearance of the data-val * attributes generated in my html and I refuse to validate my client side if I do not select the option. An alternative, apparently, is binding to a string rather than an int, and then parsing the string on the server. However, this seems hacky, and I wonder if there is an alternative that would allow me to bind to int, the default value (empty), but not required for this field

thank

In JP

+5
source share
1 answer

You should use an integer with a null value in your view model to bind to if the drop down ilst value can have a default value:

public SelectList AllProducts { get; set; }
public int? ProductID { get; set; }

, , Required:

public SelectList AllProducts { get; set; }
[Required]
public int? ProductID { get; set; }
+11

All Articles