Populate SelectList in ASP.NET MVC with enum

hotcoder picture hotcoder · Feb 7, 2014 · Viewed 18k times · Source

I have an enumeration in my Data layer and I want to use its drop down list in my website project. My enum in Data layer is:

namespace SME.DAL.Entities.Enums
{
    public enum EntityState
    {
        Open,
        Freezed,
        Canceled,
        Completed,
        Terminated,
        ReadOnly
    }
}

How can I make its select list and use it in my website's page? I'm using ASP.NET MVC 4.

Answer

Ilya picture Ilya · Feb 7, 2014

Simple example:

Controller:

public ViewResult SomeFilterAction()
{      
var EntityState = new SelectList(Enum.GetValues(typeof(EntityState)).Cast<EntityState>().Select(v => new SelectListItem
         {
             Text = v.ToString(),
             Value = ((int)v).ToString()
         }).ToList(),"Value","Text");
return View(EntityState)
}

View:

  @model System.Web.Mvc.SelectList
  @Html.DropDownList("selectedEntityState",Model)