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
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using DropDownListApp_MVC.Models;
-
- namespace DropDownListApp_MVC.Controllers
- {
- public class EmployeeController : Controller
- {
-
-
- EmployeeEntities objEmployeeEntities = new EmployeeEntities();
- public ActionResult Index()
- {
- ViewBag.List = new SelectList(objEmployeeEntities.Departments.Select(r => r.DepartmentName));
- return View();
- }
-
- public ActionResult Index1()
- {
- List<SelectListItem> items = new List<SelectListItem>();
- items.Add(new SelectListItem { Text = "IT", Value = "0" });
- items.Add(new SelectListItem { Text = "HR", Value = "1" });
- items.Add(new SelectListItem { Text = "Management", Value = "2" });
- ViewBag.List = items;
-
- return View();
- }
-
- public ActionResult Index2()
- {
- return View();
- }
-
-
-
- }
- }
Adding View
Figure 7 Add View
Index.cshtml
- @{
- ViewBag.Title = "Index";
- }
-
- <h2>Index</h2>
-
- @Html.DropDownList("List", "------Select List------")
Index1.cshtml
- @{
- ViewBag.Title = "Index1";
- }
-
- <h2>Index1</h2>
-
- @Html.DropDownList("List", "------Select List------")
Index2.cshtml
- @{
- ViewBag.Title = "Index2";
- }
-
- <h2>Index2</h2>
-
- @Html.DropDownList("List", new List<SelectListItem>
- {
- new SelectListItem{ Text="IT", Value="1"},
- new SelectListItem{ Text="HR", Value="2"},
- new SelectListItem{ Text="Management", Value="3"}
- }, "----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.