In this article, you will see how we can create dropdown list in ASP.NET MVC using HTML helper methods like HTML.DropdownList and HTML.DropdownListFor. We will be creating dropdown list from a sample MVC database. Let's take a look at each of these HTML helper examples in MVC.
Before we begin to create drop down list using Razor, let's create a new project in Visual Studio and link it with database.
Note: If you are already connected to database while working on some project, you can skip, Step 1 and Step 2, directly proceed to Step 3
Step 1: Create a new project in Visual Studio, by navigating to File-> New -> Project-> Select "ASP.NET" from left pane and Select "ASP.NET web application" from right pane, name the project, click "OK"
Select "MVC" template to generate basic MVC files and click "Ok"
Step 2: Connect to your local database, I will be connecting to database using database first approach and using EDMX entity framework file, you can right click on Models Folders and then click "Add", Select "Data" from left pane and Select "ADO.NET Entity Data Model" in right pane, name it and click "OK"
Select "Ef Designer from database"
Click "New connection", to add new connction
Enter your Server name, select database and add credentials if needed.
Select Database which you want to use (EmployeeDetails in this example)
Once, done, click "Ok".
Click "Next", select "Entity framework 6.0", select all tables using checkbox, and click "Ok".
You must see edmx file is generated in your projects, Models folder, like below
We will be using below table of "EmployeeDetails" database to create dropdown list.
Step 3: Create a View Model Class in your projects "Models" folders, right click on "Models" folder, select "Add" and then select "Class", give it a name "DropdownViewModel.cs" and click "Add"
using System.Collections.Generic;
using System.Web.Mvc;
namespace DropdownInMVC.Models
{
public class DropdownViewModel
{
//SelectListeItem type list creating Dropdown
public IEnumerable<SelectListItem> EmpList { get; set; }
//for first dropdown selected value
public string SelectedEmp { get; set; }
//for second dropdown selected value
public string SelectedEmp2 { get; set; }
}
}
Step 4: Go to your "HomeController.cs
" and create the SelectList item in your "Index ActionMethod
" to bind it with dropdown Helper in Razor View.
public ActionResult Index()
{
DropdownViewModel dropdownViewModel = new DropdownViewModel();
using (var context = new EmployeeDetailsEntities())
{
//create SelectListItem
dropdownViewModel.EmpList= context.EmpDetails.
Select(a=> new SelectListItem
{
Text = a.EmpName, // name to show in html dropdown
Value = a.EmpName // value of html dropdown
}).ToList();
}
//pass Model to view
return View(dropdownViewModel);
}
We will also create another ActionMethod
, which is of type "HttpPost
" to submit dropdown values and check it, so complete HomeController.cs code will be like below
using DropdownInMVC.Models;
using System.Linq;
using System.Web.Mvc;
namespace DropdownInMVC.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
DropdownViewModel dropdownViewModel = new DropdownViewModel();
using (var context = new EmployeeDetailsEntities())
{
//create SelectListItem
dropdownViewModel.EmpList= context.EmpDetails.
Select(a=> new SelectListItem
{
Text = a.EmpName, // name to show in html dropdown
Value = a.EmpName // value of html dropdown
}).ToList();
}
//pass Model to view
return View(dropdownViewModel);
}
//to get form values, submitted by user
[HttpPost]
public ActionResult Index(DropdownViewModel dropdownViewModel)
{
using (var context = new EmployeeDetailsEntities())
{
//create SelectListItem again
dropdownViewModel.EmpList = context.EmpDetails.
Select(a => new SelectListItem
{
Text = a.EmpName, // name to show in html dropdown
Value = a.EmpName // value of html dropdown
}).ToList();
}
//pass Model to view, but we will have selected value also this time
return View(dropdownViewModel);
}
}
}
Step 5: Go to your Index.cshtml view inside "Views"-> "Home"-> "Index.cshtml", and you the code below
@model DropdownInMVC.Models.DropdownViewModel
@{
ViewBag.Title = "Home Page";
}
<br />
@using (Html.BeginForm())
{
<div class="form-group row">
<label class="col-lg-2 control-label" for="hobies">Dropdown List using DropdownListFor:</label>
<div class="col-lg-10">
@Html.DropDownListFor(model => model.SelectedEmp, Model.EmpList, "--Select Employee--", new { @class = "form-control" })
</div>
</div>
<div class="form-group row">
<label class="col-lg-2 control-label" for="hobies">Dropdown List using DropdowwList:</label>
<div class="col-lg-10">
@Html.DropDownList("SelectedEmp2", Model.EmpList, "--Select Employee--", new { @class = "form-control" })
</div>
</div>
<div class="form-group ">
<input type="submit" value="Submit" class="btn btn-primary" />
</div>
}
@if (Model.SelectedEmp != null)
{
<div class="form-group">
You Selected value using DropdownListFor : @Model.SelectedEmp
</div>
}
@if (Model.SelectedEmp2 != null)
{
<div class="form-group">
You Selected value using DropdownList: @Model.SelectedEmp2
</div>
}
As you can see from the above code we are creating 2 dropdowns (same drop downs) but using 2 different methods of MVC Razor syntax, one is creating using HTML.DropdownListFor
and another using HTML.DropdownList
Once you have done all of the above steps, build and run it in browser, you will see output as below
Difference between HTML.DropdownList and HTML.DropdownListFor
HTML.DropdownList | HTML.DropdownListFor |
---|---|
It is weakly typed. | It is strongly typed |
Not coupled with Model, need to provide property name ("PropertyName") | Directly coupled with model (Model.PropertyName) |
Cannot use lambda expression. | Can use lambda expression. |
Creating Dropdown List in Razor View
You can also create Dropdownlist in Razor view directly, here is the sample code for it
@{
List<SelectListItem> listItems= new List<SelectListItem>();
listItems.Add(new SelectListItem
{
Text = "Example 1",
Value = "Example1"
});
listItems.Add(new SelectListItem
{
Text = "Example 2",
Value = "Example2",
Selected = true
});
listItems.Add(new SelectListItem
{
Text = "Example 3",
Value = "Example3"
});
}
@Html.DropDownListFor(model => model.DropDownMVC, listItems, "-- Select Status --")
In the above code, we are creating Dropdown list using C# Code in Razor itself, so basically, we are not using Database or controller code.
You may also like to read:
How to Create login & registration page in MVC with database (ASP.NET)
Upload file to Google Drive using Service Account in C# MVC (With Impersonation)