ASP.NET MVC Interface Controls - Dropdown List -
Populate with Data

Populated from database (LINQ to Entities):


Populated from generic collection of custom domain model objects:


Manually populated:



The Dropdown List can be populated in various ways:
- LINQ to Entities;
- LINQ to SQL;
- generic collections;
- manually;
- and many other.
C#
Populate from LINQ-to-Entities:
   
            NorthwindEntities db = new NorthwindEntities();
            var customers = from c in db.Customers
                            select new
                            {
                                c.CustomerID,
                                c.CompanyName
                            };

            SelectList customersList = new SelectList(customers.Take(10), "CustomerID", "CompanyName");

            ViewData["DdlCustomers"] = customersList;
            

Populate from manually created list:

            List items = new List();
            items.Add(new SelectListItem() { Value = "1", Text = "Item 1" });
            items.Add(new SelectListItem() { Value = "2", Text = "Item 2" });
            
            ViewData["DdlItems"] = items;
             

Populate from generic collection of custom objects (Domain Model classes):

            List products = new List();
            products.Add(new Product() { ProductID = 1, ProductName = "Product 1" });
            products.Add(new Product() { ProductID = 2, ProductName = "Product 2" });
            
            ViewData["DdlProducts"] = new SelectList(products, "ProductID", "ProductName");