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 read connection string from web.config file in ASP.NET by using the ConfigurationManager class in case you want to...
When you deploy your ASP.NET Web Application on Windows Server running IIS , there are times that you might receive...
This post will explain how to resolve the error “Handler “aspNetCore” has a bad module “AspNetCoreModuleV2” in its module list”...