Populating DropDown With AJAX Call

There are multiple ways to populate dropdown 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:
  1. <form id="myForm">  
  2.         <label for="departmentsDropdown"><b>Departments</b></label>  
  3.         <select class="form-control" id="departmentsDropdown" name="departmentsDropdown"></select>  
  4.     </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,

ajax

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:
  1. public ActionResult getDepartment()  
  2.         {  
  3.             DatabaseEntities db = new DatabaseEntities();  
  4.             return Json(db.Departments.Select(x => new  
  5.             {  
  6.                 DepartmentID = x.DepartmentID,  
  7.                 DepartmentName = x.DepartmentName  
  8.             }).ToList(), JsonRequestBehavior.AllowGet);  
  9.         }  
This above function will get data from database and send it back in Json format. Now I will write a Javascript function which will pass an Ajax call to this above method and get data from it and then this data will be displayed in the dropdown.
  1. $(document).ready(function () {  
  2.        $.ajax({  
  3.            type: "GET",  
  4.            url: "/Users/getDepartment",  
  5.            data: "{}",  
  6.            success: function (data) {  
  7.                var s = '<option value="-1">Please Select a Department</option>';  
  8.                for (var i = 0; i < data.length; i++) {  
  9.                    s += '<option value="' + data[i].DepartmentID + '">' + data[i].DepartmentName + '</option>';  
  10.                }  
  11.                $("#departmentsDropdown").html(s);  
  12.            }  
  13.        });  
  14.    });  
This above Ajax call will call the method in controller and get data from 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,
 
ajax
 
This is how we can populate a dropdown with an Ajax call in ASP.NET MVC.


Similar Articles