In ASP.NET MVC, a Dropdown (DropDownList) is used to display multiple options to the user in a simple way. The user can select one value from the list.
In this blog, we will learn:
Static dropdown (manual values)
Dynamic dropdown (data from database)
Custom dropdown (static + dynamic together)
jQuery with dropdown (change event, AJAX)
Proper syntax with examples
Easy explanation step-by-step
1. What is Dropdown in MVC?
A dropdown is created using Html Helper:
@Html.DropDownListFor()It binds with a model property and displays a list of items.
We can also use jQuery to handle events like change, load data dynamically, etc.
2. Static Dropdown (Manual Data)
Step 1: Create Model
public class Student
{
public int Id { get; set; }
public string Gender { get; set; }
}Step 2: Controller Code
public ActionResult Create()
{
List<SelectListItem> genderList = new List<SelectListItem>()
{
new SelectListItem{ Text = "Male", Value = "Male" },
new SelectListItem{ Text = "Female", Value = "Female" },
new SelectListItem{ Text = "Other", Value = "Other" }
};
ViewBag.GenderList = genderList;
return View();
}Step 3: View Code
@model Student
@Html.LabelFor(m => m.Gender)
@Html.DropDownListFor(m => m.Gender,
ViewBag.GenderList as List<SelectListItem>,
"-- Select Gender --",
new { @class = "form-control", id="ddlGender" })jQuery Example
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function () {
$("#ddlGender").change(function () {
var selectedValue = $(this).val();
alert("Selected Gender: " + selectedValue);
});
});
</script>Explanation
Text = what user sees
Value = what gets saved
ViewBag = used to pass data from controller to view
jQuery change() event triggers when user selects value
3. Dynamic Dropdown (From Database using jQuery AJAX)
Now we fetch data from the database using jQuery.
Step 1: Controller (Get Data)
public JsonResult GetDepartments()
{
using (MyDbContext db = new MyDbContext())
{
var data = db.Departments.Select(d => new
{
d.Id,
d.Name
}).ToList();
return Json(data, JsonRequestBehavior.AllowGet);
}
}
Join the conversation! Your thoughts help the community grow.