I have a view with a model of type List<string> and I want to place a drop down list on the page that contains all strings from the list as items in the drop down. I am new to MVC, how would I accomplish this?
I tried this:
@model List<string>
@Html.DropDownListFor(x => x)
but that threw an error.
To make a dropdown list you need two properties:
In your case you only have a list of string which cannot be exploited to create a usable drop down list.
While for number 2. you could have the value and the text be the same you need a property to bind to. You could use a weakly typed version of the helper:
where
Foowill be the name of the ddl and used by the default model binder. So the generated markup might look something like this:This being said a far better view model for a drop down list is the following:
and then:
and if you wanted to preselect some option in this list all you need to do is to set the
SelectedItemIdproperty of this view model to the correspondingValueof some element in theItemscollection.