Introduction
This article describes how you can bind your MVC DropDownList in different ways.
Method 1
DropDownList in Controller, using ViewBag.
Step 1
Create Controller
Right click on Controller folder in the created MVC Application and give the class name. I have given the class name Home and clicked OK.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- namespace DeleteDrop.Controllers {
- public class HomeController: Controller {
- public ActionResult Index() {
- List < SelectListItem > items = new List < SelectListItem > ();
- items.Add(new SelectListItem {
- Text = "add", Value = "Add"
- });
- items.Add(new SelectListItem {
- Text = "sub", Value = "Sub"
- });
- items.Add(new SelectListItem {
- Text = "mul", Value = "Mul"
- });
- items.Add(new SelectListItem {
- Text = "Div", Value = "Div"
- });
- ViewBag.store = items;
- return View();
- }
- }
- }
Step 2
Add View
Open a HomeController class -> right click inside Index method -> click Add View.
- @ {
- Layout = null;
- } <
- !DOCTYPE html >
- <
- html >
- <
- head >
- <
- meta name = "viewport"
- content = "width=device-width" / >
- <
- title > Index < /title> <
- /head> <
- body >
- <
- div >
- @Html.DropDownList("arithmatic", (IEnumerable < SelectListItem > ) ViewBag.store, "please select") <
- /div> <
- /body> <
- /html>
Output
Method 2
DropDownList in View.
Step 1
Create Controller
Right click on the Controller folder in the created MVC Application and give the class name. I have given the class name Home and click OK.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- namespace DeleteDrop.Controllers {
- public class HomeController: Controller {
- public ActionResult Index() {
- return View();
- }
- }
- }
Step 2
Add View
Open a HomeController class -> right click inside Index method -> click Add View.
- @ {
- Layout = null;
- } <
- !DOCTYPE html >
- <
- html >
- <
- head >
- <
- meta name = "viewport"
- content = "width=device-width" / >
- <
- title > Index < /title> <
- /head> <
- body >
- <
- div >
- <
- div style = "background:center" >
- @Html.DropDownList("dropdownname", new List < SelectListItem > {
- new SelectListItem {
- Text = "IT", Value = "1"
- },
- new SelectListItem {
- Text = "HR", Value = "2"
- }
- }, "select department") <
- /div> <
- /div> <
- /body> <
- /html>
Output