Binding an string array to a DropDownList in MVC Razor
Asked Answered
H

2

7

Do you know how easily I can bind the contents of a string array to a DropDownList in view for MVC Razor?

public static string[] AgeRagne = new string[] { "Sun", "Mon", "Tues", "Wed" };

UPDATE: Below code worked.

  @Html.DropDownListFor(
    model => model.Filter.AgeRange,
    new SelectList(Extensions.AgeRange, Model.Filter.AgeRange),
    new { @class = "search-dropdown", name = "ageRange" }
  )
Hales answered 27/4, 2012 at 8:11 Comment(1)
I'm just taking a really wild guess .. but did you mean AgeRange not AgeRagne? =>=> .. string[] AgeRagne = ...Lymphoma
L
5

a not very nice but quick way would be to do this :):

<select name="dowList" id="dowList">
    @{string[] AgeRagne = new string[] { "Sun", "Mon", "Tues", "Wed" };}
    @foreach (var dow in AgeRagne)
    {
        <option value="@dow">@dow</option>
    }
</select>

tho an htmlhelper would be the best long term stable solution.

Leopoldeen answered 27/4, 2012 at 8:28 Comment(0)
G
28

Create a SelectList with your array and pass it to your view:

SelectList list = new SelectList(AgeRagne);
ViewBag.myList = list;

Then in your view, use Html.DropDownlist:

@Html.DropDownList("myList", ViewBag.myList as SelectList)

That's all

Guanine answered 27/4, 2012 at 8:35 Comment(2)
quick and easy. one of the simplest ways to use a dropdownlistHenandchickens
One liner @Html.DropDownList("myList", new SelectList(AgeRagne))Bagatelle
L
5

a not very nice but quick way would be to do this :):

<select name="dowList" id="dowList">
    @{string[] AgeRagne = new string[] { "Sun", "Mon", "Tues", "Wed" };}
    @foreach (var dow in AgeRagne)
    {
        <option value="@dow">@dow</option>
    }
</select>

tho an htmlhelper would be the best long term stable solution.

Leopoldeen answered 27/4, 2012 at 8:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.