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.

Leave a Reply


x

Interesting BlogPosts to read

Passing Array of Integers to ASP.NET Web API REST Service
You can pass an array of integer to an ASP.NET Web Web API REST service by setting the [FromUri] att...
Webinar - Best Practices - Optimizing ASP.NET Performance, Part 1
DevExpress is hosting a webinar on the topic "Best Practices - Optimizing ASP.NET Performance, Part ...
How to Serialize Enum to String in ASP.NET ?
Sometimes when developing an web application , the developers might want to serialize Enum to its st...