Selecting an enum value from an enum DropDownList in asp.net

If you ever want a user to be able to select from an enumerated dropdown list, and have been able to create the dropdown, but haven’t been able to figure out how to select the default value, it turns out to be relatively straight forward:

Somewhere you have an enum defined:

public enum MyEnum
{
  Enum1 = 1, Enum2 = 2, Enum3 = 3
}

Somewhere in a ViewModel, you use the enum:

  public MyEnum MyEnumVariable { get; set; }

You’d think you could use it and have the correct value selected with something like this:

@Html.DropDownListFor(m=>m.MyEnumVariable,Enum.GetNames(typeof(MyEnum)).ToArray()
     .Select(f=>new SelectListItem() { Text=f,Value=f,Selected=(f==m.MyEnumVariable.ToString()) }))

But unfortunately, that doesn’t work. You have to convert f into an enum, and compare them as enums:

@Html.DropDownListFor(m=>m.MyEnumVariable,Enum.GetNames(typeof(MyEnum)).ToArray()
     .Select(f=>new SelectListItem() { 
        Text=f,Value=f,Selected=((MyEnum)Enum.Parse(typeof(MyEnum),f))==m.MyEnumVariable }))

A bit more complicated, but works like a charm!