Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the values of an enum into a SelectList

Imagine I have an enumeration such as this (just as an example):

public enum Direction{     Horizontal = 0,     Vertical = 1,     Diagonal = 2 } 

How can I write a routine to get these values into a System.Web.Mvc.SelectList, given that the contents of the enumeration are subject to change in future? I want to get each enumerations name as the option text, and its value as the value text, like this:

<select>     <option value="0">Horizontal</option>     <option value="1">Vertical</option>     <option value="2">Diagonal</option> </select> 

This is the best I can come up with so far:

 public static SelectList GetDirectionSelectList()  {     Array values = Enum.GetValues(typeof(Direction));     List<ListItem> items = new List<ListItem>(values.Length);      foreach (var i in values)     {         items.Add(new ListItem         {             Text = Enum.GetName(typeof(Direction), i),             Value = i.ToString()         });     }      return new SelectList(items);  } 

However this always renders the option text as 'System.Web.Mvc.ListItem'. Debugging through this also shows me that Enum.GetValues() is returning 'Horizontal, Vertical' etc. instead of 0, 1 as I would've expected, which makes me wonder what the difference is between Enum.GetName() and Enum.GetValue().

like image 973
Lee D Avatar asked Jul 10 '09 15:07

Lee D


People also ask

Can we convert enum to string?

We can convert an enum to string by calling the ToString() method of an Enum.

How do I display the value of an enum?

To get the value of enum we can simply typecast it to its type. In the first example, the default type is int so we have to typecast it to int. Also, we can get the string value of that enum by using the ToString() method as below.

How do you get an integer from an enum?

Getting Integer from Enum On the other hand, to get the integer value from an enum, one can do as follows, by using the getValue method. The getValue method simply returns the internal value of the enum that we store within the value variable.

Can you inherit enum?

Inheritance Is Not Allowed for Enums.


2 Answers

It's been awhile since I've had to do this, but I think this should work.

var directions = from Direction d in Enum.GetValues(typeof(Direction))            select new { ID = (int)d, Name = d.ToString() }; return new SelectList(directions , "ID", "Name", someSelectedValue); 
like image 158
Brandon Avatar answered Sep 27 '22 23:09

Brandon


There is a new feature in ASP.NET MVC 5.1 for this.

http://www.asp.net/mvc/overview/releases/mvc51-release-notes#Enum

@Html.EnumDropDownListFor(model => model.Direction) 
like image 34
Fred Avatar answered Sep 27 '22 23:09

Fred