Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I'm using a helper that i found <a href="http://blog.thomasbandt.de/39/2316/de/blog/aspnet-mvc-2-enumeration-dropdownlist-localization.html" rel="nofollow noreferrer">here</a> to populate my SelectLists with a generic enum type, i did a little modification to add the selected value though, here's how it looks like :</p> <pre><code>public static SelectList ToSelectList&lt;T&gt;(this T enumeration, string selected) { var source = Enum.GetValues(typeof(T)); var items = new Dictionary&lt;object, string&gt;(); var displayAttributeType = typeof(DisplayAttribute); foreach (var value in source) { FieldInfo field = value.GetType().GetField(value.ToString()); DisplayAttribute attrs = (DisplayAttribute)field. GetCustomAttributes(displayAttributeType, false).FirstOrDefault() items.Add(value, attrs != null ? attrs.GetName() : value.ToString()); } return new SelectList(items, "Key", "Value", selected); } </code></pre> <p>The nice thing about it is that it reads the DisplayAttribute as the title rather than the enum name. (if your enums contain spaces or you need localization then it makes your life much easier)</p> <p>So you will need to add the Display attirubete to your enums like this :</p> <pre><code>public enum User_Status { [Display(Name = "Waiting Activation")] Pending, // User Account Is Pending. Can Login / Can't participate [Display(Name = "Activated" )] Active, // User Account Is Active. Can Logon [Display(Name = "Disabled" )] Disabled, // User Account Is Diabled. Can't Login } </code></pre> <p>and this is how you use them in your views.</p> <pre><code>&lt;%: Html.DropDownList("ChangeStatus" , ListExtensions.ToSelectList(Model.statusType, user.Status))%&gt; </code></pre> <p><code>Model.statusType</code> is just an enum object of type <code>User_Status</code>. </p> <p>That's it , no more SelectLists in your ViewModels. In my example I'm refrencing an enum in my ViewModel but you can Refrence the enum type directly in your view though. I'm just doing it to make everything clean and nice.</p> <p>Hope that was helpful.</p>
 

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