Filling SelectList in ASP.NET MVC with enumeration

I have an enumeration at my data level, and I want to use its drop-down list in my website project. My listing in the data layer:

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

How can I make my selection list and use it on my website page? I am using ASP.NET MVC 4.

+3
source share
2 answers

A 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)
+15
source

Well, if you used MVC 5.1, they recently added a helper to create drop-down lists from Enums. However, since you are using MVC 4, you have to hack something.

There are several examples, and this question has already been answered many times if you were looking for it.

ASP.NET MVC?

+2

All Articles