9

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.

Jojo
  • 1,875
  • 3
  • 29
  • 29
hotcoder
  • 3,176
  • 10
  • 58
  • 96
  • The way I see it, you have 3 options: create a `SelectList` in your Action and pass it to the view **or** create a custom Html helper to do that **or** create a template for `Enum` in which you dynamically create the dropdown. The links posted in the answers bellow provide all the information needed to accomplish each of your options. – Andrei V Feb 07 '14 at 08:53

2 Answers2

22

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)
Ilya Sulimanov
  • 7,636
  • 6
  • 47
  • 68
  • If you move this logic inside a Html helper or even a template, you don't have to explicitly call the action every time your need an "enum dropdown". – Andrei V Feb 07 '14 at 08:56
3

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?

Community
  • 1
  • 1
Erik Funkenbusch
  • 92,674
  • 28
  • 195
  • 291