Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The solution from PaulTheCyclist is spot on. But I wouldn't use RESX (I'd have to add a new .resx file for each new enum??)</p> <p>Here is my HtmlHelper Expression:</p> <pre><code>public static MvcHtmlString EnumDropDownListFor&lt;TModel, TEnum&gt;(this HtmlHelper&lt;TModel&gt; htmlHelper, Expression&lt;Func&lt;TModel, TEnum&gt;&gt; expression, object attributes = null) { //Get metadata from enum var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData); var enumType = GetNonNullableModelType(metadata); var values = Enum.GetValues(enumType).Cast&lt;TEnum&gt;(); //Convert enumeration items into SelectListItems var items = from value in values select new SelectListItem { Text = value.ToDescription(), Value = value.ToString(), Selected = value.Equals(metadata.Model) }; //Check for nullable value types if (metadata.IsNullableValueType) { var emptyItem = new List&lt;SelectListItem&gt; { new SelectListItem {Text = string.Empty, Value = string.Empty} }; items = emptyItem.Concat(items); } //Return the regular DropDownlist helper return htmlHelper.DropDownListFor(expression, items, attributes); } </code></pre> <p>Here is how I declare my enums:</p> <pre><code>[Flags] public enum LoanApplicationType { [Description("Undefined")] Undefined = 0, [Description("Personal Loan")] PersonalLoan = 1, [Description("Mortgage Loan")] MortgageLoan = 2, [Description("Vehicle Loan")] VehicleLoan = 4, [Description("Small Business")] SmallBusiness = 8, } </code></pre> <p>And here is the call from a Razor View:</p> <pre><code>&lt;div class="control-group span2"&gt; &lt;div class="controls"&gt; @Html.EnumDropDownListFor(m =&gt; m.LoanType, new { @class = "span2" }) &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Where <code>@Model.LoanType</code> is an model property of the LoanApplicationType type</p> <p><strong>UPDATE:</strong> Sorry, forgot to include code for the helper function ToDescription()</p> <pre><code>/// &lt;summary&gt; /// Returns Description Attribute information for an Enum value /// &lt;/summary&gt; /// &lt;param name="value"&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public static string ToDescription(this Enum value) { if (value == null) { return string.Empty; } var attributes = (DescriptionAttribute[]) value.GetType().GetField( Convert.ToString(value)).GetCustomAttributes(typeof (DescriptionAttribute), false); return attributes.Length &gt; 0 ? attributes[0].Description : Convert.ToString(value); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload