Created
August 25, 2013 18:36
-
-
Save pseudomuto/6335482 to your computer and use it in GitHub Desktop.
Blog Code: Showing Enums as a Select List in MVC with Razor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public enum FieldType | |
{ | |
Text = 1, | |
HTML = 2, | |
[Display(Name = "Date/Time")] | |
DateTime = 3, | |
Number = 4, | |
[Display(Name = "Dropdown List")] | |
DropdownList = 5 | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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 | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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