Enum datatype is used to define the named constants (i.e., the constant having a name and value). Enum can be used to populate a DropDownList control because Enum members have string names and an integer value associated with each one. See the below example with all steps.
Enum
Create the following Enum which we want to populate in the dropdown.
- public enum Country
- {
- [Display(Name = "India")]
- India,
- [Display(Name = "United States of America")]
- usa,
- [Display(Name = "United Kingdom")]
- uk,
- [Display(Name = "Australia")]
- Australia
- }
Model
In Model, we need to define a property of Enum.
- public class CountryModel
- {
- public Country country { get; set; }
- }
Action
Create an action result for View.
- public IActionResult Country()
- {
- return View();
- }
View
In View, call the model and include namespace where the County Enum is stored.
- @model Demo.Models.CountryModel
- @using Demo.Models
- @{
- ViewData["Title"] = "Country";
- }
Select Country
- <select asp-for="Country" asp-items="Html.GetEnumSelectList<Country>()" ></select>
Hope this blog will help you in understanding how to bind a dropdownlist with Enum in ASP.NET Core MVC.
Your feedback is always welcome.