How to create Dropdownlist in ASP.NET MVC from Enum Data source ?

If you have a Enum and want to bind it to the Dropdownlist in ASP.NET MVC 4 Page , you can do this easily with the help of LINQ and Anonymous properties.

How to create Dropdownlist in ASP.NET MVC from Enum Data source ?

Below is a sample sourecode demonstrating how to create Dropdownlist in ASP.NET MVC from Enum Data source .

Controller

public class IndexController : Controller

{

public ActionResult Index()

{

var Movies = from BlockbusterMovies data in Enum.GetValues(typeof(BlockbusterMovies))

select new { id = data, MovieName = data.ToString() };

ViewData["movies"] = new SelectList(Movies, "ID", "MovieName", BlockbusterMovies.Nanban);

return View();

}

}

public enum BlockbusterMovies

{

Vishwaroopam = 1,

Thuppaki = 2,

Nanban = 3,

Mankatha = 4,

Velayutham = 5

}

View

@Html.DropDownList("movies")

How to create Dropdownlist in ASP.NET MVC from Enum Datasource ?

How to create Dropdownlist in ASP.NET MVC from Enum Datasource ?

In the above example , i have an enum BlockbusterMovies which needs to be bound to the dropdownlist. Enum.GetValues is used to get the values from the Enum which is used in the LINQ Query to form the List and then assigned to the ViewData which is bound to the dropdownlist.

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.
Pin It

Leave a Reply

Your email address will not be published. Required fields are marked *