Rendering Enums as drop downs in ASP.NET MVC

This is a handy view, for automatically turning an Enum property on a ViewModel into a drop down list.

@model object
@functions
{
  IEnumerable ToSelectListItems(Enum enumObj)
  {
    foreach (var obj in Enum.GetValues(enumObj.GetType()))
    { 
      yield return new SelectListItem
      {
        Value = obj.ToString(),
        Text = Enum.GetName(enumObj.GetType(), obj).Replace("_", " ")
      };
    }
  }
}

@if (this.Model is Enum)
{
  @Html.DropDownListFor(m => m, ToSelectListItems(this.Model as Enum))
  @Html.ValidationMessageFor(m => m)
}
else
{
  @Html.TextBox("",ViewData.TemplateInfo.FormattedModelValue,new { @class = "text-box single-line" })
}

Simply call it ‘string.cshtml’ and add it to your Views\Shared\EditorTemplates folder.

Now when you call  @Html.EditorForModel(Model as object) in your view, you get Enum properties rendered as drop downs. Underscores in the Enum names will be displayed as spaces.

Advertisements