title: Passing enum values to a ListBoxFor in ASP.NET MVC3
body: <p>I've read up a good bit on creating a <code>SelectList</code> from an <code>Enum</code> to populate a drop down list, and found many solutions. Here are a few examples</p>
  
  <pre><code>public static IEnumerable&lt;SelectListItem&gt; GetEnumSelectList&lt;T&gt;()
  {
      return (Enum.GetValues(typeof(T)).Cast&lt;T&gt;().Select(
          enu =&gt; new SelectListItem() { Text = enu.ToString(), Value = enu.ToString() })).ToList();
  }
  
  public static SelectList ToSelectList&lt;TEnum&gt;(this TEnum enumObj) 
      where TEnum : struct, IComparable, IFormattable, IConvertible
  {
      var values = from TEnum e in Enum.GetValues(typeof(TEnum))
                   select new { Id = e, Name = e.ToString() };
      return new SelectList(values, "Id", "Name", enumObj);
  }
  </code></pre>
  
  <p>Both of these (and most others) return the names of the enum values for both <code>Text</code> and <code>Value</code>. </p>
  
  <p>Example</p>
  
  <pre><code>public enum WeatherInIreland
  {
       NotGreat = 0,
       Bad = 1,
       Awful = 2
  } 
  </code></pre>
  
  <p>Results from the first two methods</p>
  
  <pre><code>&lt;select id="Weather" name="Weather"&gt;
      &lt;option value="NotGreat"&gt;NotGreat&lt;/option&gt;
      &lt;option value="Bad"&gt;Bad&lt;/option&gt;
      &lt;option value="Awful"&gt;Awful&lt;/option&gt;
  &lt;/select&gt;
  </code></pre>
  
  <p>However, I wanted to return the <em>name</em> for <code>Text</code> and the <em>int value</em> for the <code>Value</code>. </p>
  
  <pre><code>&lt;select id="Weather" name="Weather"&gt;
      &lt;option value="0"&gt;NotGreat&lt;/option&gt;
      &lt;option value="1"&gt;Bad&lt;/option&gt;
      &lt;option value="2"&gt;Awful&lt;/option&gt;
  &lt;/select&gt;
  </code></pre>
  
  <p>This is the code I came up with. </p>
  
  <pre><code>public static System.Web.Mvc.SelectList ToSelectList&lt;TEnum&gt;(this TEnum enumObj) where TEnum : struct, IComparable, IFormattable, IConvertible
  {
      List&lt;SelectListItem&gt; selist = new List&lt;SelectListItem&gt;();
      foreach (int value in Enum.GetValues(typeof(TEnum)))
      {
          TEnum type = (TEnum)Enum.Parse(typeof(TEnum), value.ToString());
          selist.Add(new SelectListItem { Value = value.ToString(), Text = type.ToString() });
      }
      return new System.Web.Mvc.SelectList(selist, "Value", "Text");
  }
  </code></pre>
  
  <p>As you can see it's a modified version of the last method above. It works, but it is ugly. I have to iterate over the <code>Enum</code> values as ints and then separately parse each one to return the name. Surely there's a better way of doing this? </p>