ASP MVC Html.DropDownList with Values and Default Selection

Category: .NET C# Programming Tags: ,
May 20, 2015

ASP.NET MVC (Razor) has some great features and the Html Helpers take care of a lot of the coding for you. But sometimes I just want to do a simple dropdown, like:

<select>
<option value=”1″ selected=”selected”>1</option>
<option value=”2″>2</option>
<option value=”3″>3</option>
</select>

It’s nice to use a Helper; I can pass the selected value (or even a model) and it saves me messing about with bits of code. But the Html.DropDownList wants me to pass an IEnumerable<SelectListItem> for the values and sometimes when I am developing I just want to add ad-hoc values to the list and pass the default in the ViewBag. Here’s how to do it:

@Html.DropDownList("myvalues",
new SelectList(new[]
  {
    new SelectListItem { Text = "1", Value = "1" },
    new SelectListItem { Text = "2", Value = "2" },
    new SelectListItem { Text = "3", Value = "3" },
  }, "Value", "Text", ViewBag.myValue),
  new { @class = "myClass" })

In production apps it’s probably better not to use code like this in the View but it’s useful for a quick combo.