Its useful to be able to have a helper that converts a Enum typed property from an MVC Model directly into a drop down list without any messing about creating lists of possible values etc.
I found this answer on StackOverflow which has example code for just such a helper: EnumDropDownListFor. However, like a few who have tried it I found some issues around getting it to work to pre-select the value held in the Model’s property.
There are a number of suggested tweaks in the comments to the above answer, but I believe the root of the problem is better described by another answer on StackOverflow that I came across while investigating.
As it says, the root of the issue is a misunderstanding of the behaviours of the different overloads on DropDownList. To quote from the linked answer:
1: Html.DropDownList(string name) looks for a view model property of name and type IEnumerable. It will use the selected item (SelectListItem.Selected == true) from the list, unless there is a form post value of the same name.
2: Html.DropDownList(string name, IEnumerable selectList) uses the items from selectList, but not their selected values. The selected is found by resolving name in the view model (or post data) and matching it against the SelectListItem.Value. Even if the value cannot be found (or is null), it still won't use the selected value from the list of SelectListItems.
So, to fix the EnumDropDownListFor helper we need to tweak it slightly to work with the second of these overloads. Happily we don’t need a little of the code responsible for setting Selected/SelectedValue as the DropDownList overload does this for us.
My version follows. I’ve also added the extra overloads to allow for use of htmlAttributes etc: