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" }
  )
1
  • 1
    I'm just taking a really wild guess .. but did you mean AgeRange not AgeRagne? =>=> .. string[] AgeRagne = ... Commented Aug 2, 2016 at 2:15

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

quick and easy. one of the simplest ways to use a dropdownlist
One liner @Html.DropDownList("myList", new SelectList(AgeRagne))
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.