Meds
Meds

Reputation: 71

DropDownList from IEnumerable<string> model

I have a IEnumerable list model containing different city names, I would like to make a DropDownList from this model, I saw an example that work, but for creating links, I think we can do the same thing for a Dropdownlist by looping through the list. How could I do that ?

@model IEnumerable<string>





    @foreach (var link in Model)
    {
      // ????
    }

Upvotes: 0

Views: 10911

Answers (3)

von v.
von v.

Reputation: 17108

Use the htmlhelper that is already available for you

@Html.DropDownList("cities", new SelectList(Model))

Upvotes: 9

Segev -CJ- Shmueli
Segev -CJ- Shmueli

Reputation: 1621

The very simple, and basic form (without moving the SelectList to the controller) is :

@model IEnumerable<string>
@{
var selectList = new SelectList(Model) ;

}

@Html.DropDownList("MyDropDownListName", selectList)

Although I would prefer creating an extension to the HtmlHelper class, or using a "strong named" dropdownlist @Html.DropDownListFor(myvar=>myvar.City, selectList)

Upvotes: 3

Ant P
Ant P

Reputation: 25221

If you don't want to use HtmlHelpers, which, from your question, it sounds like you don't, you can use the following iterative method for an IEnumerable<string>:

<select name="myFormInputName">
@foreach (var link in Model)
{
  <option value="@(link)">@(link)</option>
}
</select>

Upvotes: 3

Related Questions