Bind Dropdown on Selection Change of Another Dropdown in MVC Using Ajax and JQuery

Here I'm going to explain how can we bind a dropdown in a selection change of another dropdown in MVC using jQuery and Ajax. For example, we have a dropdown that shows a list of states, and another dropdown that will show the list of cities of the selected state. Initially our page has only the state list dropdown bound. On the selection change of the state list dropdown we will bind the city list drop down using an Ajax call. We are using a database first approach here. Let's start..

Step 1: Create a database with two tables.

  • States
  • Cities
  1. State table has the following columns.

    1. StateId (int Primary Key Identity)
    2. StateName (varchar(500))

    A snippet of this table is attached.

    table

  2. Cities Table has the following columns.

    1.CityId(int Primary Key Identity)
    2.CityName (varchar(500))
    3.StateId (int)

    table

Step 2 : Open Visual Studio, Create New Project, then click ASP.NET MVC 4 Web Application

Name your project. In my case it is “RunTimeDropDownBinding

project

Step 3: Create an empty template. I'm using here Razor View Engine.

template

Step 4: Now we've to add a controller which returns a view. Right click on Controllers, then Add, and then click Controller.

controller

A pop up window will ask the name of the controller. My controller name is “HomeController.” Name your controller and click Add.

add

Below is the screenshot of the controller that will be created,

code

Step 5:

Create a view that is returned by Index action of Home Controller. To do this right click at Index action method in home controller – Add View.

code

A popup window will open. Just click ok, because it displays all the things as we need.
(According to our need we can change them, but at this point we don't need it.)

view

Click on  the“Add” button.

The following screen will appear.

screen

Step 6:

Now we are going to add data model, which will be responsible for communicating with database. Here we are using a “Database first” approach. So the model will be automatically generated from database. To achieve this Jjst right click in your solution folder. In my case RuntimeDropDownBinding- Add- New Item.

new item

A pop up window will open.

model

Click on ADO.NET Entity Data Model. Name it “DropDownDataModel.” Click on Add. Next window will appear like this,

EFD

Select “EF Designer from DataBase” and click Next.

A new pop up window will open,

data model

Click on new connection. The following window will appear,

properties

Select your source name. I have my database locally so i used “.”. Expand Select or enter database name. Select your database. In my case it is “CITYSTATE.” Click on “Test Connection.” If you get “Connection OK” message, click on OK. A new window will appear.

framework

Its asking “Which version of Entity Framework do you want to use?” I've selected Entity Framework 5.0. Click on “Next” the following window will appear,

table

It's asking for you to choose your database object and setting. I had only two tables inthe database, so I've checked both. Click on finish.

At this stage entity framework has been added to your project and the database is mapped with the application. See the screenshot below

ef

Now we have successfully added “DropDownDataModel” to our project. Our model is generated. Now we'll start with the coding part.

Step 7: Now open your index.cshtml file which is in Views-Home-index.cshtml,

 Add a reference to jQuery. (To save Jquery I've created a “Script” folder inside root directory and copied jQuery.min.js file there).

Add reference of jQuery like this,

<script src=”~/Scripts/jquery.min.js”></script>

Now create two dropdown like this,

  1. <select id="stateDropDown" onchange="getCityList()">  
  2. </select><br/><br/>  
  3.   
  4. <select id="cityDropDown">  
  5. </select>   
Step 7:

Now we have to bind state list when the page loads so first we've to get all states fromthe database, and then bind them with drop down “stateDropDown.”

For this open home controller from Controller folder and get to Index action of the controller.

Write following code in Index action of Home Controller, 
  1. using (CITYSTATEEntities cITYSTATEEntities = new CITYSTATEEntities())   
  2. {  
  3. ViewBag.StateList = cITYSTATEEntities.STATES.ToList();  
  4. }  
At this point we've adde List of States in ViewBag.

Step 8:

Now we have to change our view, so that StateList added, in ViewBag we can bind with dropdown. For this use this code,
  1. <select id="stateDropDown" onchange="getCityList()">  
  2. @foreach (var item in ViewBag.StateList)  
  3. {  
  4. <text>  
  5. <option value="@item.StateID">@item.StateName</option>  
  6. </text>  
  7. }  
  8. </select><br/><br/> 
Step 9:

Now our “stateDropDown” has been bound with the list of cities. In “onchange” event of this dropdown we'll  make an Ajax call using Jquery library to get the list of corresponding cities.
  1. <script>  
  2.     function getCityList()  
  3. {  
  4.         debugger;  
  5.         var stateId = $("#stateDropDown").val();  
  6.         $.ajax  
  7.         ({  
  8.             url: '/Home/GetCityList',  
  9.             type: 'POST',  
  10.             datatype: 'application/json',  
  11.             contentType: 'application/json',  
  12.             data: JSON.stringify({  
  13.                 stateId: +stateId  
  14.             }),  
  15.             success: function(result)  
  16.           {  
  17.                 $("#cityDropDown").html("");  
  18.                 $.each($.parseJSON(result), function(i, city)  
  19.                 {  
  20.                     $("#cityDropDown").append($('<option></option>').val(city.CityID).html(city.CityName))  
  21.                 })  
  22.   
  23.             },  
  24.             error: function()  
  25.             {  
  26.                 alert("Whooaaa! Something went wrong..")  
  27.             },  
  28.         });  
  29.     }  
  30. </script>  
and in the home controller we have to add one more action method that will be responsible for getting the list of cities associated with the selected state and return the list of cities in the form of Json.
  1. public ActionResult GetCityList(string stateID)  
  2. {  
  3.     List < CITy > lstcity = new List < CITy > ();  
  4.     int stateiD = Convert.ToInt32(stateID);  
  5.     using(CITYSTATEEntities cITYSTATEEntities = new CITYSTATEEntities())  
  6.     {  
  7.         lstcity = (cITYSTATEEntities.CITIES.Where(x => x.StateId == stateiD)).ToList < CITy > ();  
  8.     }  
  9.     JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();  
  10.     string result = javaScriptSerializer.Serialize(lstcity);  
  11.     return Json(result, JsonRequestBehavior.AllowGet);  
  12. }  
This will return List of cities in the form of Json. And in the success event of Ajax call I've bound the list of cities with cityDropDown. This code will do this,
  1. success: function(result)  
  2. {  
  3.     $("#cityDropDown").html("");  
  4.     $.each($.parseJSON(result), function(i, city)   
  5.      {  
  6.         $("#cityDropDown").append($('<option></option>').val(city.CityID).html(city.CityName))  
  7.     })  
  8.   
  9. }, 
Step 10: Finally our Home controller should look like this,

final

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using System.Web.Script.Serialization;  
  7.   
  8. namespace RuntimeDropDownBinding.Controllers  
  9. {  
  10.     public class HomeController: Controller   
  11.     {  
  12.         //  
  13.         // GET: /Home/  
  14.   
  15.         public ActionResult Index()   
  16.         {  
  17.   
  18.             //Here I'm Binding list of state to drop down  
  19.             using(CITYSTATEEntities cITYSTATEEntities = new CITYSTATEEntities())  
  20.             {  
  21.                 ViewBag.StateList = cITYSTATEEntities.STATES.ToList();  
  22.             }  
  23.             return View();  
  24.         }  
  25.   
  26.         [HttpPost]  
  27.         public ActionResult GetCityList(string stateID)   
  28.         {  
  29.             //Here I'll bind the list of cities corresponding to selected state's state id  
  30.             List < CITy > lstcity = new List < CITy > ();  
  31.             int stateiD = Convert.ToInt32(stateID);  
  32.             using(CITYSTATEEntities cITYSTATEEntities = new CITYSTATEEntities())   
  33.             {  
  34.                 lstcity = (cITYSTATEEntities.CITIES.Where(x => x.StateId == stateiD)).ToList < CITy > ();  
  35.             }  
  36.             JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();  
  37.             string result = javaScriptSerializer.Serialize(lstcity);  
  38.             return Json(result, JsonRequestBehavior.AllowGet);  
  39.         }  
  40.   
  41.     }  
  42. }  
Step 11: Our View must look like this.

view
  1. @ {  
  2.     ViewBag.Title = "Index";  
  3. }  
  4.   
  5. < h2 > Drop Down Binding < /h2> < script src = "~/Scripts/jquery-1.8.3.min.js" > < /script> < select id = "stateDropDown"  
  6. onchange = "getCityList()" >  
  7.     @foreach(var item in ViewBag.StateList) { < text >  
  8.             < option value = "@item.StateID" > @item.StateName < /option> < /text>  
  9.     } < /select><br/ > < br / >  
  10.   
  11.     < select id = "cityDropDown" >  
  12.     < /select>  
  13.   
  14.   
  15. < script >  
  16.     function getCityList()  
  17.     {  
  18.         debugger;  
  19.         var stateId = $("#stateDropDown").val();  
  20.         $.ajax({  
  21.             url: '/Home/GetCityList',  
  22.             type: 'POST',  
  23.             datatype: 'application/json',  
  24.             contentType: 'application/json',  
  25.             data: JSON.stringify({  
  26.                 stateId: +stateId  
  27.             }),  
  28.             success: function(result)  
  29.             {  
  30.                 $("#cityDropDown").html("");  
  31.                 $.each($.parseJSON(result), function(i, city)   
  32.                  {  
  33.                     $("#cityDropDown").append($('<option></option>').val(city.CityID).html(city.CityName))  
  34.                 })  
  35.   
  36.             },  
  37.             error: function()  
  38.             {  
  39.                 alert("Whooaaa! Something went wrong..")  
  40.             },  
  41.         });  
  42.     } < /script>

Read more articles on ASP.NET Programming:

Up Next
    Ebook Download
    View all
    Learn
    View all