Binding an string array to a DropDownList in MVC Razor

ary picture ary · Apr 27, 2012 · Viewed 30.1k times · Source

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" }
  )

Answer

Robby Shaw picture Robby Shaw · Apr 27, 2012

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