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.
- State table has the following columns.
1. StateId (int Primary Key Identity)
2. StateName (varchar(500))
A snippet of this table is attached.
- Cities Table has the following columns.
1.CityId(int Primary Key Identity)
2.CityName (varchar(500))
3.StateId (int)
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”
Step 3: Create an empty template. I'm using here Razor View Engine.
Step 4: Now we've to add a controller which returns a view. Right click on Controllers, then Add, and then click Controller.
A pop up window will ask the name of the controller. My controller name is “HomeController.” Name your controller and click Add.
Below is the screenshot of the controller that will be created,
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.
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.)
Click on the“Add” button.
The following screen will appear.
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.
A pop up window will open.
Click on ADO.NET Entity Data Model. Name it “DropDownDataModel.” Click on Add. Next window will appear like this,
Select “EF Designer from DataBase” and click Next.
A new pop up window will open,
Click on new connection. The following window will appear,
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.
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,
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
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,
- <select id="stateDropDown" onchange="getCityList()">
- </select><br/><br/>
-
- <select id="cityDropDown">
- </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,
- using (CITYSTATEEntities cITYSTATEEntities = new CITYSTATEEntities())
- {
- ViewBag.StateList = cITYSTATEEntities.STATES.ToList();
- }
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,
- <select id="stateDropDown" onchange="getCityList()">
- @foreach (var item in ViewBag.StateList)
- {
- <text>
- <option value="@item.StateID">@item.StateName</option>
- </text>
- }
- </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.
- <script>
- function getCityList()
- {
- debugger;
- var stateId = $("#stateDropDown").val();
- $.ajax
- ({
- url: '/Home/GetCityList',
- type: 'POST',
- datatype: 'application/json',
- contentType: 'application/json',
- data: JSON.stringify({
- stateId: +stateId
- }),
- success: function(result)
- {
- $("#cityDropDown").html("");
- $.each($.parseJSON(result), function(i, city)
- {
- $("#cityDropDown").append($('<option></option>').val(city.CityID).html(city.CityName))
- })
-
- },
- error: function()
- {
- alert("Whooaaa! Something went wrong..")
- },
- });
- }
- </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.
- public ActionResult GetCityList(string stateID)
- {
- List < CITy > lstcity = new List < CITy > ();
- int stateiD = Convert.ToInt32(stateID);
- using(CITYSTATEEntities cITYSTATEEntities = new CITYSTATEEntities())
- {
- lstcity = (cITYSTATEEntities.CITIES.Where(x => x.StateId == stateiD)).ToList < CITy > ();
- }
- JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
- string result = javaScriptSerializer.Serialize(lstcity);
- return Json(result, JsonRequestBehavior.AllowGet);
- }
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,
- success: function(result)
- {
- $("#cityDropDown").html("");
- $.each($.parseJSON(result), function(i, city)
- {
- $("#cityDropDown").append($('<option></option>').val(city.CityID).html(city.CityName))
- })
-
- },
Step 10: Finally our Home controller should look like this,
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using System.Web.Script.Serialization;
-
- namespace RuntimeDropDownBinding.Controllers
- {
- public class HomeController: Controller
- {
-
-
-
- public ActionResult Index()
- {
-
-
- using(CITYSTATEEntities cITYSTATEEntities = new CITYSTATEEntities())
- {
- ViewBag.StateList = cITYSTATEEntities.STATES.ToList();
- }
- return View();
- }
-
- [HttpPost]
- public ActionResult GetCityList(string stateID)
- {
-
- List < CITy > lstcity = new List < CITy > ();
- int stateiD = Convert.ToInt32(stateID);
- using(CITYSTATEEntities cITYSTATEEntities = new CITYSTATEEntities())
- {
- lstcity = (cITYSTATEEntities.CITIES.Where(x => x.StateId == stateiD)).ToList < CITy > ();
- }
- JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
- string result = javaScriptSerializer.Serialize(lstcity);
- return Json(result, JsonRequestBehavior.AllowGet);
- }
-
- }
- }
Step 11: Our View must look like this.
- @ {
- ViewBag.Title = "Index";
- }
-
- < h2 > Drop Down Binding < /h2> < script src = "~/Scripts/jquery-1.8.3.min.js" > < /script> < select id = "stateDropDown"
- onchange = "getCityList()" >
- @foreach(var item in ViewBag.StateList) { < text >
- < option value = "@item.StateID" > @item.StateName < /option> < /text>
- } < /select><br/ > < br / >
-
- < select id = "cityDropDown" >
- < /select>
-
-
- < script >
- function getCityList()
- {
- debugger;
- var stateId = $("#stateDropDown").val();
- $.ajax({
- url: '/Home/GetCityList',
- type: 'POST',
- datatype: 'application/json',
- contentType: 'application/json',
- data: JSON.stringify({
- stateId: +stateId
- }),
- success: function(result)
- {
- $("#cityDropDown").html("");
- $.each($.parseJSON(result), function(i, city)
- {
- $("#cityDropDown").append($('<option></option>').val(city.CityID).html(city.CityName))
- })
-
- },
- error: function()
- {
- alert("Whooaaa! Something went wrong..")
- },
- });
- } < /script>
Read more articles on ASP.NET Programming: