Dropdown list with MVC5.1 – now out of the box!

Last year I made this post showing a clean way to render a dropdown list in MVC.

Recently MS released MVC5.1 (prerelase) and excitingly it now has Enum support.

Jon Galloway has written an excellent post outlining this change. The .Net team have added a new HTMLHelper extension called EnumDropDownListFor that will render an Enum as a dropdown box (or radio button list).

How does this compare to the long winded solution I outlined last year, I hear no one asking?

To recap, we want to render a dropdown list that looks like:


with our view rendering our model with one line.


We no longer need the custom Htmlhelper Extension EnumDropDownListFor used in the previous solution, as that now ships with MVC5.1 (well, not the same implementation!). We do, however, still want to be culture aware and use a Resx file to contain the resources of the actual names to display on screen. I’d now recommend using display attributes in the Enum to identify the resource. This will leave our Enum and model looking like:

public enum AirlinePreference
    [Display(Name = "AirlinePreference_BritishAirways",
                ResourceType = typeof(Resources.Enums))]
    [Display(Name = "AirlinePreference_EasyJet", 
                ResourceType = typeof(Resources.Enums))]
    [Display(Name = "AirlinePreference_RyanAir",
                ResourceType = typeof(Resources.Enums))]
    [Display(Name = "AirlinePreference_Virgin",
                ResourceType = typeof(Resources.Enums))]

public class PersonViewModel 
    [Display(Name="First Name")]
    public string FirstName { get; set; }

    [Display(Name = "Last Name")]
    public string LastName { get; set; }

    [Display(Name = "Airline Preference")]
    public AirlinePreference? AirlinePreference { get; set; }

For reference our resx file looks like this


Compile it, run it, go to the Add Person page and you’ll see the dropdown list as before…

5.1 is still prerelease and at the time of writing @Html.EditorForModel will not render an Enum dropdown list. It currently needs a push in the form of an Enum template (as described in Jon’s blog) to know how to display an Enum.
With my lean hat on, for the purpose of this blog the following will suffice.

Create a view called Enum.cshtml and put it in the EditorTemplate folder


Add this one line

@Html.EnumDropDownListFor(x => x)

Now go the Add Person page and voila, a DropDownList is present.