Sunday, January 11, 2009

Making a dropdownlist in ASP.Net MVC from an enum

Some times your business objects use a simple enum to indicate something, for instance a status. For one of my projects I have a TaskStatus defined like this:

public enum TaskStatus
{
    NotStarted,
    InProgress,
    Waiting,
    Finished,
    Cancelled
}

Nothing exciting here. Now I want to turn this into a SelectList that can be used with the Html.DropDownList helper. Turns out this is embarrassingly easy using LINQ and anonymous methods:

  1: var statuses = from TaskStatus s in Enum.GetValues(typeof(TaskStatus))
  2:                select new { ID = s, Name = s.ToString() };
  3: ViewData["taskStatus"] = new SelectList(statuses, "ID", "Name", task.Status);


Now I can just use it in my view using the helper method:



  1: <td><b>Status:</b></td><td><%=Html.DropDownList("taskStatus")%></td></tr> 


Easy peasy. :)

2 comments:

rash said...

Hi

Thanks for the post! I could not understand what task.staus means in this line:
ViewData["taskStatus"] = new SelectList(statuses, "ID", "Name", task.Status);

please let me know.
Thanks

Havremunken said...

Hi,

Sorry, I didn't see your comment until now - not the most active blog in the world, I'm afraid. :|

task.Status was never explained, you're right. In this post, task is the variable that we're editing in the html form, and the Status-field is the field that contains the current value of the enumeration.

Did that make sense? :)