Today we will make a cascading dropdown application of Country, State and City in JQuery
N.B.~ We are using JQuery 1.6.1
Let us first make the entities.We will have 3 entities here viz, Country, State and City
Country Entity(Country.cs)
/// <summary>
/// Summary description for Country
/// </summary>
public class Country
{
public string CountryName { get; set; }
public string CountryCode { get; set; }
}
State Entity(State.cs)
/// <summary>
/// Summary description for State
/// </summary>
public class State
{
public string StateName { get; set; }
public string StateCode { get; set; }
public string CountryCode { get; set; }
}
City Entity(City.cs)
/// <summary>
/// Summary description for City
/// </summary>
public class City
{
public string CityName { get; set; }
public string CityCode { get; set; }
public string StateCode { get; set; }
}
Now make the datasouce as under
DataSource(DataSource.cs)
using System.Collections.Generic;
/// <summary>
/// Summary description for DataSource
/// </summary>
public class DataSource
{
List _country = new List();
List _state = new List();
List _city = new List();
public List GetCountryList()
{
_country.Clear();
CountryData();
return _country;
}
public List GetStateList()
{
_state.Clear();
StateData();
return _state;
}
public List GetCityList()
{
_city.Clear();
CityData();
return _city;
}
#region Data Source
private void CountryData()
{
_country.Add(new Country { CountryName = "--Select A Country --", CountryCode = "None" });
_country.Add(new Country { CountryName = "India", CountryCode = "IN" });
_country.Add(new Country { CountryName = "USA", CountryCode = "US" });
_country.Add(new Country { CountryName = "Canada", CountryCode = "CA" });
_country.Add(new Country { CountryName = "Singapore", CountryCode = "SI" });
}
private void StateData()
{
_state.Add(new State { StateName = "IndState1", CountryCode = "IN", StateCode = "INS1" });
_state.Add(new State { StateName = "IndState2", CountryCode = "IN", StateCode = "INS2" });
_state.Add(new State { StateName = "IndState3", CountryCode = "IN", StateCode = "INS3" });
_state.Add(new State { StateName = "IndState4", CountryCode = "IN", StateCode = "INS4" });
_state.Add(new State { StateName = "USAState1", CountryCode = "US", StateCode = "USS1" });
_state.Add(new State { StateName = "USAState2", CountryCode = "US", StateCode = "USS2" });
_state.Add(new State { StateName = "USAState3", CountryCode = "US", StateCode = "USS3" });
_state.Add(new State { StateName = "USAState4", CountryCode = "US", StateCode = "USS4" });
_state.Add(new State { StateName = "CANState1", CountryCode = "CA", StateCode = "CAS1" });
_state.Add(new State { StateName = "CANState2", CountryCode = "CA", StateCode = "CAS2" });
_state.Add(new State { StateName = "CANState3", CountryCode = "CA", StateCode = "CAS3" });
_state.Add(new State { StateName = "CANState4", CountryCode = "CA", StateCode = "CAS4" });
_state.Add(new State { StateName = "SINGState1", CountryCode = "SI", StateCode = "SIS1" });
_state.Add(new State { StateName = "SINGState2", CountryCode = "SI", StateCode = "SIS2" });
_state.Add(new State { StateName = "SINGState3", CountryCode = "SI", StateCode = "SIS3" });
_state.Add(new State { StateName = "SINGState4", CountryCode = "SI", StateCode = "SIS4" });
}
private void CityData()
{
_city.Add(new City { CityName = "IndianState1City1", CityCode="City1", StateCode = "INS1" });
_city.Add(new City { CityName = "IndianState1City2", CityCode = "City2", StateCode = "INS1" });
_city.Add(new City { CityName = "IndianState2City1", CityCode = "City3", StateCode = "INS2" });
_city.Add(new City { CityName = "IndianState2City2", CityCode = "City4", StateCode = "INS2" });
_city.Add(new City { CityName = "IndianState3City1", CityCode = "City5", StateCode = "INS3" });
_city.Add(new City { CityName = "IndianState3City2", CityCode = "City6", StateCode = "INS3" });
_city.Add(new City { CityName = "IndianState4City1", CityCode = "City7", StateCode = "INS4" });
_city.Add(new City { CityName = "IndianState4City2", CityCode = "City8", StateCode = "INS4" });
_city.Add(new City { CityName = "USAState1City1", CityCode = "City9", StateCode = "USS1" });
_city.Add(new City { CityName = "USAState1City2", CityCode = "City10", StateCode = "USS1" });
_city.Add(new City { CityName = "USAState2City1", CityCode = "City11", StateCode = "USS2" });
_city.Add(new City { CityName = "USAState2City2", CityCode = "City12", StateCode = "USS2" });
_city.Add(new City { CityName = "USAState3City1", CityCode = "City13", StateCode = "USS3" });
_city.Add(new City { CityName = "USAState3City2", CityCode = "City14", StateCode = "USS3" });
_city.Add(new City { CityName = "USAState4City1", CityCode = "City15", StateCode = "USS4" });
_city.Add(new City { CityName = "USAState4City2", CityCode = "City16", StateCode = "USS4" });
_city.Add(new City { CityName = "CanadaState1City1", CityCode = "City17", StateCode = "CAS1" });
_city.Add(new City { CityName = "CanadaState1City2", CityCode = "City18", StateCode = "CAS1" });
_city.Add(new City { CityName = "CanadaState2City1", CityCode = "City19", StateCode = "CAS2" });
_city.Add(new City { CityName = "CanadaState2City2", CityCode = "City20", StateCode = "CAS2" });
_city.Add(new City { CityName = "CanadaState3City1", CityCode = "City21", StateCode = "CAS3" });
_city.Add(new City { CityName = "CanadaState3City2", CityCode = "City22", StateCode = "CAS3" });
_city.Add(new City { CityName = "CanadaState4City1", CityCode = "City23", StateCode = "CAS4" });
_city.Add(new City { CityName = "CanadaState4City2", CityCode = "City24", StateCode = "CAS4" });
_city.Add(new City { CityName = "SingaporeState1City1", CityCode = "City25", StateCode = "SIS1" });
_city.Add(new City { CityName = "SingaporeState1City2", CityCode = "City26", StateCode = "SIS1" });
_city.Add(new City { CityName = "SingaporeState2City1", CityCode = "City27", StateCode = "SIS2" });
_city.Add(new City { CityName = "SingaporeState2City2", CityCode = "City28", StateCode = "SIS2" });
_city.Add(new City { CityName = "SingaporeState3City1", CityCode = "City29", StateCode = "SIS3" });
_city.Add(new City { CityName = "SingaporeState3City2", CityCode = "City30", StateCode = "SIS3" });
_city.Add(new City { CityName = "SingaporeState4City1", CityCode = "City31", StateCode = "SIS4" });
_city.Add(new City { CityName = "SingaporeState4City2", CityCode = "City32", StateCode = "SIS4" });
}
#endregion
}
Next create a page by the name CascadingDropdown.aspx with 3 drop down controls
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Cascading Dropdown Example </title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
Country
</td>
<td>
<asp:DropDownList ID="ddlCountry" runat="server" />
</td>
</tr>
<tr>
<td>
State
</td>
<td>
<asp:DropDownList ID="ddlState" runat="server"/>
</td>
</tr>
<tr>
<td>
City
</td>
<td>
<asp:DropDownList ID="ddlCity" runat="server" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
Now load the value in the Country dropdown in the Page_Load event of the CascadingDropdown.aspx.cs file
using System;
public partial class CascadingDropdown : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateCountry();
}
}
private void PopulateCountry()
{
DataSource ds = new DataSource();
ddlCountry.DataSource = ds.GetCountryList();
ddlCountry.DataValueField = "CountryCode";
ddlCountry.DataTextField = "CountryName";
ddlCountry.DataBind();
}
}
Once done , add the below script tag in the CascadingDropdown.aspx page
<script type="text/javascript" src="JQuery/jquery-1.6.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#ddlCountry").change(function() {
$("#ddlState").html("");
var CountryID = $("#ddlCountry option:selected").val();
$.getJSON('ServerResponse.aspx?CountryID=' + CountryID, function(states) {
$.each(states, function() {
$("#ddlState").append($("<option></option>").val(this['StateCode']).html(this['StateName']));
});
});
});
});
</script>
Once the user changes the Country Dropdown, first of all we are picking up the CountryID and forming the query string.
We are using the getJSON method of JQuery for getting the server response in json format. Once receive, we are looping it
thru by using each() method of JQuery and populating the State Dropdown
Now let us look into as what is happening in the ServerResponse.aspx.cs file's Page_Load event
using System;
using System.Linq;
using System.Text;
public partial class ServerResponse : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string CountryID = Request.QueryString["CountryID"];
if (CountryID != null)
{
DataSource ds = new DataSource();
StringBuilder strStates = new StringBuilder();
//Filter the state list based on country id
var stateList = ds.GetStateList().Where(i => i.CountryCode == CountryID).ToList();
//Convert StateList object to JSON Format
strStates.Append("[");
for (int i = 0; i < stateList.Count(); i++)
{
strStates.Append("{");
strStates.Append("\"StateCode\":\"" + stateList[i].StateCode + "\",");
strStates.Append("\"StateName\":\"" + stateList[i].StateName + "\"");
strStates.Append("},");
}
strStates.Append("]");
var finalString = strStates.ToString().Substring(0, strStates.ToString().Length - 2) + "]";
//Send the response to the client
Response.ContentType = "application/json";
Response.ContentEncoding = Encoding.UTF8;
Response.Write(finalString.ToString());
Response.End();
}
}
}
First of all, we are filtering the StateList based on the Country ID passed. Then we are converting the StateList object to
JSON Format and finally sending the response to the client in JSON format.
If we now run the application, then we will be able to see the changes hapenning in the State dropdown based on the country
changes
The same applies for State and City drop down also
So the full code for CascadingDropdown.aspx will be
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Cascading Dropdown Example </title>
<script type="text/javascript" src="JQuery/jquery-1.6.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#ddlCountry").change(function() {
$("#ddlState").html("");
var CountryID = $("#ddlCountry option:selected").val();
$.getJSON('ServerResponse.aspx?CountryID=' + CountryID, function(states) {
$.each(states, function() {
$("#ddlState").append($("<option></option>").val(this['StateCode']).html(this['StateName']));
});
});
});
$("#ddlState").change(function() {
$("#ddlCity").html("");
var StateID = $("#ddlState option:selected").val();
$.getJSON('ServerResponse.aspx?StateID=' + StateID, function(cities) {
$.each(cities, function() {
$("#ddlCity").append($("<option></option>").val(this['CityCode']).html(this['CityName']));
});
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
Country
</td>
<td>
<asp:DropDownList ID="ddlCountry" runat="server" />
</td>
</tr>
<tr>
<td>
State
</td>
<td>
<asp:DropDownList ID="ddlState" runat="server"/>
</td>
</tr>
<tr>
<td>
City
</td>
<td>
<asp:DropDownList ID="ddlCity" runat="server" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
And for ServerResponse.aspx.cs file's Page_Load event it will be
using System;
using System.Linq;
using System.Text;
public partial class ServerResponse : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string CountryID = Request.QueryString["CountryID"];
string StateID = Request.QueryString["StateID"];
if (CountryID != null)
{
DataSource ds = new DataSource();
StringBuilder strStates = new StringBuilder();
//Filter the state list based on country id
var stateList = ds.GetStateList().Where(i => i.CountryCode == CountryID).ToList();
//Convert StateList object to JSON Format
strStates.Append("[");
for (int i = 0; i < stateList.Count(); i++)
{
strStates.Append("{");
strStates.Append("\"StateCode\":\"" + stateList[i].StateCode + "\",");
strStates.Append("\"StateName\":\"" + stateList[i].StateName + "\"");
strStates.Append("},");
}
strStates.Append("]");
var finalString = strStates.ToString().Substring(0, strStates.ToString().Length - 2) + "]";
//Send the response to the client
Response.ContentType = "application/json";
Response.ContentEncoding = Encoding.UTF8;
Response.Write(finalString.ToString());
Response.End();
}
if (StateID != null)
{
DataSource ds = new DataSource();
StringBuilder strCities = new StringBuilder();
//Filter the city list based on state id
var cityList = ds.GetCityList().Where(i => i.StateCode == StateID).ToList();
//Convert CityList object to JSON Format
strCities.Append("[");
for (int i = 0; i < cityList.Count(); i++)
{
strCities.Append("{");
strCities.Append("\"CityCode\":\"" + cityList[i].StateCode + "\",");
strCities.Append("\"CityName\":\"" + cityList[i].CityName + "\"");
strCities.Append("},");
}
strCities.Append("]");
var finalString = strCities.ToString().Substring(0, strCities.ToString().Length - 2) + "]";
//Send the response to the client
Response.ContentType = "application/json";
Response.ContentEncoding = Encoding.UTF8;
Response.Write(finalString.ToString());
Response.End();
}
}
}
N.B.~ The above code can be improved further. It is only for demo purpose
I hope this will to those who have started learning JQuery like me