Enum dropdown bind in asp.net MVC razor

By 3rd January 2019MVC

How do you create dropdown list from enum in asp.net MVC

  1. Write Enum
public enum MeetingType
        {
            [Description("First")]
            FIRST= 1,
            [Description("Second")]
            SECOND= 2,
            [Description("Third")]
            THIRD= 3
        }

public string Name{get;set;}

After Enum we will write get select list code from enum in controller section in those controller that will have the view of dropdown.

public ActionResult GetDropdown()
{
var enumData = from Demo e in Enum.GetValues(typeof(Demo))
                           select new
                           {
                               Value= (int)e,
                               Text= e
                           };
            ViewBag.EnumList = new SelectList(enumData,"Value","Text");
return View();
}

Here Demo is the Enum name and we created a list type of selectlist for dropdown.

Now we can use this ViewBag.EnumList in our dropdown list.

Razor Code:

@Html.DropDownList("Name", ViewBag.EnumList as SelectList, "Select Type", new { @class = "form-control" })

If you use @Html.DropDownListFor() Then for strongly bind code is below:

@Html.DropDownListFor(x => x.Name, (IEnumerable<SelectListItem>)ViewBag.EnumList, "Select Type", new { @class = "form-control" })

And now you can bind your dropdown with your Name model attribute.

Leave a Reply