Introduction

This article shows how to use the dropdownlist helper in MVC applications.

  • Index: wrapping data coming from Entity Framework (EF).
  • Index1: wrapping data coming from the Controller's Action Result.
  • Index2: wrapping data inside the view.

Create an ASP.Net MVC 4 Web Application


Figure 1 Web Application

Choose Internet Application


Figure 2 Internet Application

Add an EmployeeController


Figure 3 Add EmployeeController

Set up an Entity Framework


Figure 4 Entity Framework


Figure 5 Data Connection

Figure 6 Data Connection Object

Employeecontroller.cs

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Mvc;
  6. using DropDownListApp_MVC.Models;
  7. namespace DropDownListApp_MVC.Controllers
  8. {
  9. public class EmployeeController : Controller
  10. {
  11. //
  12. // GET: /Employee/
  13. EmployeeEntities objEmployeeEntities = new EmployeeEntities();
  14. public ActionResult Index()
  15. {
  16. ViewBag.List = new SelectList(objEmployeeEntities.Departments.Select(r => r.DepartmentName));
  17. return View();
  18. }
  19. public ActionResult Index1()
  20. {
  21. List<SelectListItem> items = new List<SelectListItem>();
  22. items.Add(new SelectListItem { Text = "IT", Value = "0" });
  23. items.Add(new SelectListItem { Text = "HR", Value = "1" });
  24. items.Add(new SelectListItem { Text = "Management", Value = "2" });
  25. ViewBag.List = items;
  26. return View();
  27. }
  28. public ActionResult Index2()
  29. {
  30. return View();
  31. }
  32. }
  33. }

Adding View


Figure 7 Add View

Index.cshtml

  1. @{
  2. ViewBag.Title = "Index";
  3. }
  4. <h2>Index</h2>
  5. @Html.DropDownList("List", "------Select List------")

Index1.cshtml

  1. @{
  2. ViewBag.Title = "Index1";
  3. }
  4. <h2>Index1</h2>
  5. @Html.DropDownList("List", "------Select List------")

Index2.cshtml

  1. @{
  2. ViewBag.Title = "Index2";
  3. }
  4. <h2>Index2</h2>
  5. @Html.DropDownList("List", new List<SelectListItem>
  6. {
  7. new SelectListItem{ Text="IT", Value="1"},
  8. new SelectListItem{ Text="HR", Value="2"},
  9. new SelectListItem{ Text="Management", Value="3"}
  10. }, "----Select List----")

The output of the application as in the following screenshot.


Figure 8 Output 1

Figure 9 Output 2

Figure 10 Output3

Summary

In this article we saw how to use a dropdownlist helper in MVC applications.

Happy coding.