NOTE: it is assumed that you are using MVC2.
If I ever need a strongly typed drop-down menu (list of countries in this case), I use 2 properties in my ViewModel.
public IEnumerable<SelectListItem> Countries { get; set; } public int CountryID { get; set; }
I am doing a preliminary conversion of my list to IEnumerable<SelectListItem> in my action using code like this. (This assumes a country class with a name and a unique identifier).
viewModel.Countries = Repository.ListAll().Select(c => new SelectListItem { Text = c.Name, Value = c.ID });
Then in my strongly typed view, I use:
<%= Html.DropDownListFor(model => model.CountryID, Model.Countries) %>
This is great because when you send back to a strongly typed action (getting the same CountryID mode), CountryID will be the identifier of the selected country.
Another advantage is if they have a verification problem. All you have to do is populate the .Countries list, pass the view model back to the view and automatically select the correct value.
source share