Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding an string array to a DropDownList in MVC Razor

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" }
  )
like image 618
ary Avatar asked Apr 27 '12 08:04

ary


People also ask

How do I bind a dropdown in MVC Razor?

Binding MVC DropDownList with Static Values Just add an Html helper for DropDownList and provide a static list of SelectListItem. The values added as SelectListItem will be added and displayed in the DropDownList. In this way, you do not need to add anything to Controller Action.


1 Answers

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

like image 90
Robby Shaw Avatar answered Sep 22 '22 15:09

Robby Shaw