Populate dropdown with enumeration items in ASP.NET Core

We can bind a dropdown with enumeration items without creating a look up table.

In Get enumeration items as a list in C# article we saw that how we can get enumeration items as a list to bind it to a data control.

Here is the enumeration we have been working with:

 enum UserStatus
    {
        [Description("Pending Verification")]
        PendingVerification = 1,
        [Description("Pending Admin Approval")]
        PendingAdminApproval = 2,
        [Description("Active")]
        Active = 3,
        [Description("Blocked by Admin")]
        BlockedByAdmin = 4
    }

We will slightly modify the utility class (perhaps the method) to make it available for binding to a dropdown in ASP.NET Core MVC.

Here is the modified utility class:

public class Enum<T> where T : struct, IConvertible
    {

        public static List<SelectListItem> GetListItems()
        {
            List<SelectListItem> items = new List<SelectListItem>();


            Type type = typeof(T);

            if (type.IsEnum)
            {
                Array values = System.Enum.GetValues(type);

                foreach (int val in values)
                {

                    var memInfo = type.GetMember(type.GetEnumName(val));
                    var descriptionAttributes = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
                    SelectListItem item = new SelectListItem
                    {
                        Text = val.ToString(),
                        Value = val.ToString()
                    };
                    if (descriptionAttributes.Length > 0)
                    {

                        item.Text = ((DescriptionAttribute)descriptionAttributes[0]).Description;
                    }
                    items.Add(item);


                }

            }
            return items;
        }
    }

Here is the view model:

public class UserViewModel
    {
        //Other properties
        public int UserStatus { get; set; }

        public List<SelectListItem> UserStatuses { get; set; }
    }

Controller action will look like this:

 public IActionResult Index()
        {
            UserViewModel viewModel = new UserViewModel()
            {
                UserStatuses = Enum<UserStatus>.GetListItems()
            };
            return View(viewModel);
        }

and finally the view code will look like this:

@model UserViewModel
@{
    ViewData["Title"] = "Manage Users";
}

<form>
    <select asp-for="@Model.UserStatus" asp-items="@Model.UserStatuses"></select>
</form>

Hopefully it will help you to bind dropdowns with enumerations.

Comments
Share it