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.

Leave A Reply

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

You May Also Like

You can pass an array of integer to an ASP.NET Web Web API REST service by setting the [FromUri] attribute...
One of the common ways to refresh webpage every few mins is by using JavaScript or HTML Meta tag. For...
This post will provide the list of some of the top ASP.NET based Content Management Systems (CMS) that you may...