Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate SelectList in ASP.NET MVC with enum [duplicate]

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.

like image 554
hotcoder Avatar asked Feb 07 '14 08:02

hotcoder


2 Answers

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)
like image 52
Ilya Avatar answered Nov 18 '22 23:11

Ilya


Well, if you were using MVC 5.1, they recently added a helper to create dropdowns from Enums. However, since you're using MVC 4 you will have to hack something together.

There are some examples out there, and this has been answered many times already on this site if you had searched for it.

How do you create a dropdownlist from an enum in ASP.NET MVC?

like image 38
Erik Funkenbusch Avatar answered Nov 19 '22 00:11

Erik Funkenbusch