Skip to content

Instantly share code, notes, and snippets.

@pseudomuto
Created August 25, 2013 18:36
Show Gist options
  • Save pseudomuto/6335482 to your computer and use it in GitHub Desktop.
Save pseudomuto/6335482 to your computer and use it in GitHub Desktop.
Blog Code: Showing Enums as a Select List in MVC with Razor
public enum FieldType
{
Text = 1,
HTML = 2,
[Display(Name = "Date/Time")]
DateTime = 3,
Number = 4,
[Display(Name = "Dropdown List")]
DropdownList = 5
}
@model FieldType
@using System.ComponentModel.DataAnnotations
<select name="@ViewData.TemplateInfo.GetFullHtmlFieldName(string.Empty)">
@foreach (var name in Enum.GetNames(typeof(FieldType))) {
<option selected="selected" value="@name">@DisplayName(name)</option>
}
</select>
@helper DisplayName(string name) {
var attr = typeof(FieldType).GetField(name).GetCustomAttributes(typeof(DisplayAttribute), false).FirstOrDefault() as DisplayAttribute;
if (attr != null)
{
@attr.Name
}
else
{
@name
}
}
<div class="editor-label">@Html.LabelFor(model => model.Type)</div>
<div class="editor-field">@Html.EditorFor(model => model.Type)
@Html.ValidationMessageFor(model => model.Type)
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment