Add DropDownList Value from Database in ASP.NET MVC

First add model customer

  1. public partial class customer  
  2. {  
  3. public int Id { getset; }  
  4.   
  5. [Required]  
  6. [StringLength(50)]  
  7. public string Name { getset; }  
  8.   
  9. [Required]  
  10. [StringLength(50)]  
  11. public string City { getset; }  
  12. }  
Add controller CustomerController
  1. private ModelCustomer db = new ModelCustomer();  
  2. public ActionResult Index()  
  3. {  
  4. var q = db.customers.Select(c => new SelectListItem { Value = c.City, Text = c.City });  
  5. ViewBag.City = q.ToList();  
  6. return View();  
  7. }  
  8. Now Add View:  
  9. @model WebApplication1.Models.customer  
  10.   
  11. @{  
  12. Layout = null;  
  13. }  
  14.   
  15. <!DOCTYPE html>  
  16.   
  17. <html>  
  18. <head>  
  19. <meta name="viewport" content="width=device-width" />  
  20. <title>Index</title>  
  21. </head>  
  22. <body>  
  23. <div>   
  24. @Html.DropDownList("City",ViewBag.City as SelectList,"Select City")   
  25. </div>  
  26. </body>  
  27. </html>  
Now build project and values of City column of Customer table can be seen in dropdownlist.