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

2

10

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.

Meraz answered 7/2, 2014 at 8:43 Comment(1)
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.Kerman
R
23

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)
Relation answered 7/2, 2014 at 8:51 Comment(1)
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".Kerman
R
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?

Rabideau answered 7/2, 2014 at 8:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.