Introduction:
In this article,i am going to explain about how to create a cascading dropdownlist using ajax/javascript.
Main:
What is Cascading DropDown List?
Cascading DropDownList means a series of dependent DropDownLists where one DropDownList is dependent on the parent or previous DropDownList and is populated based on the item selected by the user.
See the below examble,
In default.aspx page,
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CS.aspx.cs" Inherits="_Default" EnableEventValidation = "false" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type = "text/javascript">
var pageUrl = '<%=ResolveUrl("~/CS.aspx")%>'
function PopulateContinents() {
$("#<%=ddlCountries.ClientID%>").attr("disabled", "disabled");
$("#<%=ddlCities.ClientID%>").attr("disabled", "disabled");
if ($('#<%=ddlContinents.ClientID%>').val() == "0") {
$('#<%=ddlCountries.ClientID %>').empty().append('<option selected="selected" value="0">Please select</option>');
$('#<%=ddlCities.ClientID %>').empty().append('<option selected="selected" value="0">Please select</option>');
}
else {
$('#<%=ddlCountries.ClientID %>').empty().append('<option selected="selected" value="0">Loading...</option>');
$.ajax({
type: "POST",
url: pageUrl + '/PopulateCountries',
data: '{continentId: ' + $('#<%=ddlContinents.ClientID%>').val() + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnCountriesPopulated,
failure: function(response) {
alert(response.d);
}
});
}
}
function OnCountriesPopulated(response) {
PopulateControl(response.d, $("#<%=ddlCountries.ClientID %>"));
}
</script>
<script type = "text/javascript">
function PopulateCities() {
$("#<%=ddlCities.ClientID%>").attr("disabled", "disabled");
if ($('#<%=ddlCountries.ClientID%>').val() == "0") {
$('#<%=ddlCities.ClientID %>').empty().append('<option selected="selected" value="0">Please select</option>');
}
else {
$('#<%=ddlCities.ClientID %>').empty().append('<option selected="selected" value="0">Loading...</option>');
$.ajax({
type: "POST",
url: pageUrl + '/PopulateCities',
data: '{countryId: ' + $('#<%=ddlCountries.ClientID%>').val() + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnCitiesPopulated,
failure: function(response) {
alert(response.d);
}
});
}
}
function OnCitiesPopulated(response) {
PopulateControl(response.d, $("#<%=ddlCities.ClientID %>"));
}
</script>
<script type = "text/javascript">
function PopulateControl(list, control) {
if (list.length > 0) {
control.removeAttr("disabled");
control.empty().append('<option selected="selected" value="0">Please select</option>');
$.each(list, function() {
control.append($("<option></option>").val(this['Value']).html(this['Text']));
});
}
else {
control.empty().append('<option selected="selected" value="0">Not available<option>');
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
Continents:<asp:DropDownList ID="ddlContinents" runat="server" AppendDataBoundItems="true"
onchange = "PopulateContinents();">
<asp:ListItem Text = "Please select" Value = "0"></asp:ListItem>
</asp:DropDownList>
<br /><br />
Country:<asp:DropDownList ID="ddlCountries" runat="server"
onchange = "PopulateCities();">
<asp:ListItem Text = "Please select" Value = "0"></asp:ListItem>
</asp:DropDownList>
<br /><br />
City:<asp:DropDownList ID="ddlCities" runat="server">
<asp:ListItem Text = "Please select" Value = "0"></asp:ListItem>
</asp:DropDownList>
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick = "Submit" />
</div>
</form>
</body>
</html>
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CS.aspx.cs" Inherits="_Default" EnableEventValidation = "false" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script src="scripts/jquery-1.4.1.min.js" type="text/javascript"></script> <script type = "text/javascript"> var pageUrl = '<%=ResolveUrl("~/CS.aspx")%>' function PopulateContinents() { $("#<%=ddlCountries.ClientID%>").attr("disabled", "disabled"); $("#<%=ddlCities.ClientID%>").attr("disabled", "disabled"); if ($('#<%=ddlContinents.ClientID%>').val() == "0") { $('#<%=ddlCountries.ClientID %>').empty().append('<option selected="selected" value="0">Please select</option>'); $('#<%=ddlCities.ClientID %>').empty().append('<option selected="selected" value="0">Please select</option>'); } else { $('#<%=ddlCountries.ClientID %>').empty().append('<option selected="selected" value="0">Loading...</option>'); $.ajax({ type: "POST", url: pageUrl + '/PopulateCountries', data: '{continentId: ' + $('#<%=ddlContinents.ClientID%>').val() + '}', contentType: "application/json; charset=utf-8", dataType: "json", success: OnCountriesPopulated, failure: function(response) { alert(response.d); } }); } } function OnCountriesPopulated(response) { PopulateControl(response.d, $("#<%=ddlCountries.ClientID %>")); } </script> <script type = "text/javascript"> function PopulateCities() { $("#<%=ddlCities.ClientID%>").attr("disabled", "disabled"); if ($('#<%=ddlCountries.ClientID%>').val() == "0") { $('#<%=ddlCities.ClientID %>').empty().append('<option selected="selected" value="0">Please select</option>'); } else { $('#<%=ddlCities.ClientID %>').empty().append('<option selected="selected" value="0">Loading...</option>'); $.ajax({ type: "POST", url: pageUrl + '/PopulateCities', data: '{countryId: ' + $('#<%=ddlCountries.ClientID%>').val() + '}', contentType: "application/json; charset=utf-8", dataType: "json", success: OnCitiesPopulated, failure: function(response) { alert(response.d); } }); } } function OnCitiesPopulated(response) { PopulateControl(response.d, $("#<%=ddlCities.ClientID %>")); } </script> <script type = "text/javascript"> function PopulateControl(list, control) { if (list.length > 0) { control.removeAttr("disabled"); control.empty().append('<option selected="selected" value="0">Please select</option>'); $.each(list, function() { control.append($("<option></option>").val(this['Value']).html(this['Text'])); }); } else { control.empty().append('<option selected="selected" value="0">Not available<option>'); } } </script> </head> <body> <form id="form1" runat="server"> <div> Continents:<asp:DropDownList ID="ddlContinents" runat="server" AppendDataBoundItems="true" onchange = "PopulateContinents();"> <asp:ListItem Text = "Please select" Value = "0"></asp:ListItem> </asp:DropDownList> <br /><br /> Country:<asp:DropDownList ID="ddlCountries" runat="server" onchange = "PopulateCities();"> <asp:ListItem Text = "Please select" Value = "0"></asp:ListItem> </asp:DropDownList> <br /><br /> City:<asp:DropDownList ID="ddlCities" runat="server"> <asp:ListItem Text = "Please select" Value = "0"></asp:ListItem> </asp:DropDownList> <br /> <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick = "Submit" /> </div> </form> </body> </html> |
In default.aspx.cs page,
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Collections;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.PopulateContinents();
}
}
private void PopulateContinents()
{
String strConnString = ConfigurationManager
.ConnectionStrings["conString"].ConnectionString;
String strQuery = "select ID, ContinentName from Continents";
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
con.Open();
ddlContinents.DataSource = cmd.ExecuteReader();
ddlContinents.DataTextField = "ContinentName";
ddlContinents.DataValueField = "ID";
ddlContinents.DataBind();
con.Close();
}
}
}
[System.Web.Services.WebMethod]
public static ArrayList PopulateCountries(int continentId)
{
ArrayList list = new ArrayList();
String strConnString = ConfigurationManager
.ConnectionStrings["conString"].ConnectionString;
String strQuery = "select ID, CountryName from Countries where ContinentID=@ContinentID";
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@ContinentID", continentId);
cmd.CommandText = strQuery;
cmd.Connection = con;
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
list.Add(new ListItem(
sdr["CountryName"].ToString(),
sdr["ID"].ToString()
));
}
con.Close();
return list;
}
}
}
[System.Web.Services.WebMethod]
public static ArrayList PopulateCities(int countryId)
{
ArrayList list = new ArrayList();
String strConnString = ConfigurationManager
.ConnectionStrings["conString"].ConnectionString;
String strQuery = "select ID, CityName from Cities where CountryID=@CountryID";
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@CountryID", countryId);
cmd.CommandText = strQuery;
cmd.Connection = con;
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
list.Add(new ListItem(
sdr["CityName"].ToString(),
sdr["ID"].ToString()
));
}
con.Close();
return list;
}
}
}
protected void Submit(object sender, EventArgs e)
{
string continent = Request.Form[ddlContinents.UniqueID];
string country = Request.Form[ddlCountries.UniqueID];
string city = Request.Form[ddlCities.UniqueID];
}
}
using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Configuration; using System.Data.SqlClient; using System.Data; using System.Collections; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { this.PopulateContinents(); } } private void PopulateContinents() { String strConnString = ConfigurationManager .ConnectionStrings["conString"].ConnectionString; String strQuery = "select ID, ContinentName from Continents"; using (SqlConnection con = new SqlConnection(strConnString)) { using (SqlCommand cmd = new SqlCommand()) { cmd.CommandType = CommandType.Text; cmd.CommandText = strQuery; cmd.Connection = con; con.Open(); ddlContinents.DataSource = cmd.ExecuteReader(); ddlContinents.DataTextField = "ContinentName"; ddlContinents.DataValueField = "ID"; ddlContinents.DataBind(); con.Close(); } } } [System.Web.Services.WebMethod] public static ArrayList PopulateCountries(int continentId) { ArrayList list = new ArrayList(); String strConnString = ConfigurationManager .ConnectionStrings["conString"].ConnectionString; String strQuery = "select ID, CountryName from Countries where ContinentID=@ContinentID"; using (SqlConnection con = new SqlConnection(strConnString)) { using (SqlCommand cmd = new SqlCommand()) { cmd.CommandType = CommandType.Text; cmd.Parameters.AddWithValue("@ContinentID", continentId); cmd.CommandText = strQuery; cmd.Connection = con; con.Open(); SqlDataReader sdr = cmd.ExecuteReader(); while (sdr.Read()) { list.Add(new ListItem( sdr["CountryName"].ToString(), sdr["ID"].ToString() )); } con.Close(); return list; } } } [System.Web.Services.WebMethod] public static ArrayList PopulateCities(int countryId) { ArrayList list = new ArrayList(); String strConnString = ConfigurationManager .ConnectionStrings["conString"].ConnectionString; String strQuery = "select ID, CityName from Cities where CountryID=@CountryID"; using (SqlConnection con = new SqlConnection(strConnString)) { using (SqlCommand cmd = new SqlCommand()) { cmd.CommandType = CommandType.Text; cmd.Parameters.AddWithValue("@CountryID", countryId); cmd.CommandText = strQuery; cmd.Connection = con; con.Open(); SqlDataReader sdr = cmd.ExecuteReader(); while (sdr.Read()) { list.Add(new ListItem( sdr["CityName"].ToString(), sdr["ID"].ToString() )); } con.Close(); return list; } } } protected void Submit(object sender, EventArgs e) { string continent = Request.Form[ddlContinents.UniqueID]; string country = Request.Form[ddlCountries.UniqueID]; string city = Request.Form[ddlCities.UniqueID]; } } |
For Downloading the jquery script file,just click jquery2
Conclusion:
Hope this helps,
Happy Coding.
nice post. thanks.
Thank you for useful info.
I like that you
think. Thank you for share very
thanks for great informations It’s a wonderful
Download Internet Explorer 8
I like that you
think. Thank you for share very
Hi there, I found your blog via Google while searching for first aid for a heart attack and your post looks very interesting for me.
Lots of great information and inspiration, both of which we all need, thanks for this.
Awesome!, Thanks!
thanks alot but this example didn’t work with me can you help me