There are multiple ways to populate dropdowns in ASP.NET MVC. But using jQuery Ajax for populating a dropdown is easy and fast. So in this article I will show you how to populate a dropdown from the database using jQuery ajax.
I am assuming that you have a table in your database named "Department" and we will get data from that table.
First of all in a create a View of ay name (I am creating one with the name ViewProducts) and add the following code.
<form id="myForm">
<label for="departmentsDropdown"><b>Departments</b></label>
<select class="form-control" id="departmentsDropdown" name="departmentsDropdown"></select>
</form>
This is the html code for our dropdown. It is not populated yet so it will not have any data now. It will look like.
Now we have created our dropdown but it does not have any data yet. I will write a function (method) in the controller that will get data from the database for all departments from the "Department" table.
public ActionResult getDepartment()
{
DatabaseEntities db = new DatabaseEntities();
return Json(db.Departments.Select(x => new
{
DepartmentID = x.DepartmentID,
DepartmentName = x.DepartmentName
}).ToList(), JsonRequestBehavior.AllowGet);
}
This above function will get data from the database and send it back in JSON format. Now I will write a Javascript function that will pass an Ajax call to this above method and get data from it and then this data will be displayed in the dropdown.
$(document).ready(function () {
$.ajax({
type: "GET",
url: "/Users/getDepartment",
data: "{}",
success: function (data) {
var s = '<option value="-1">Please Select a Department</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].DepartmentID + '">' + data[i].DepartmentName + '</option>';
}
$("#departmentsDropdown").html(s);
}
});
});
This above Ajax call will call the method in the controller and get data from the controller and then this data will be displayed in the dropdown. After these steps, if I run my project, the dropdown will look like the following.
This is how we can populate a dropdown with an Ajax call in ASP.NET MVC.