Aspdotnet-Suresh

aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

jQuery Cascading Dropdown List in Asp.net with Example

Oct 6, 2013
Introduction:

Here I will explain cascading dropdown list using jQuery in asp.net example or jQuery cascading dropdown example in asp.net using c#, vb.net.

Description:

In my previous article I explained how to populate dropdown based on other dropdown using asp.net, Ajax cascading dropdown with database in asp.net, Bind asp.net dropdown in jQuery. Now I will explain how to implement cascading dropdown list using jQuery in asp.net.

Here I will explain jQuery cascading dropdown example with three dropdowns Country dropdown, State dropdown, Region dropdown. Here we need to populate states dropdown based on country dropdown and region dropdown based on states dropdown selection for that we need to design three tables in SQL Server like as shown below

Country Table

Column Name
Data Type
Allow Nulls
CountryId
int(set identity property=true)
No
CountryName
varchar(50)
Yes
State Table

Column Name
Data Type
Allow Nulls
StateId
int(set identity property=true)
No
StateName
varchar(50)
Yes
CountryId
int
Yes
Region Table

Column Name
Data Type
Allow Nulls
RegionId
int(set identity property=true)
No
RegionName
varchar(50)
Yes
StateId
int
Yes
Once we create above tables we need to insert some dummy data like as shown below 

Country Table

State Table


 Region Table 


Now we need to write the code like as shown below in your aspx page


<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>jQuery Cascading Dropdown Example</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>Country</td>
<td>
<asp:DropDownList ID="ddlcountries" runat="server"></asp:DropDownList>
</td>
</tr>
<tr>
<td>State</td>
<td>
<asp:DropDownList ID="ddlstate" runat="server"></asp:DropDownList>
</td>
</tr>
<tr>
<td>Region</td>
<td>
<asp:DropDownList ID="ddlcity" runat="server"></asp:DropDownList>
</td>
</tr>
</table>
</div>
</form>
<script type="text/javascript">
$(function() {
$('#<%=ddlstate.ClientID %>').attr('disabled', 'disabled');
$('#<%=ddlcity.ClientID %>').attr('disabled', 'disabled');
$('#<%=ddlstate.ClientID %>').append('<option selected="selected" value="0">Select State</option>');
$('#<%=ddlcity.ClientID %>').empty().append('<option selected="selected" value="0">Select Region</option>');
$('#<%=ddlcountries.ClientID %>').change(function() {
var country = $('#<%=ddlcountries.ClientID%>').val()
$('#<%=ddlstate.ClientID %>').removeAttr("disabled");
$('#<%=ddlcity.ClientID %>').empty().append('<option selected="selected" value="0">Select Region</option>');
$('#<%=ddlcity.ClientID %>').attr('disabled', 'disabled');
$.ajax({
type: "POST",
url: "jQueryCascadingDropdownExample.aspx/BindStates",
data: "{'country':'" + country + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
var j = jQuery.parseJSON(msg.d);
var options;
for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>'
}
$('#<%=ddlstate.ClientID %>').html(options)
},
error: function(data) {
alert('Something Went Wrong')
}
});
});
$('#<%=ddlstate.ClientID %>').change(function() {
var stateid = $('#<%=ddlstate.ClientID%>').val()
$('#<%=ddlcity.ClientID %>').removeAttr("disabled");
$.ajax({
type: "POST",
url: "jQueryCascadingDropdownExample.aspx/BindRegion",
data: "{'state':'" + stateid + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
var j = jQuery.parseJSON(msg.d);
var options;
for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>'
}
$('#<%=ddlcity.ClientID %>').html(options)
},
error: function(data) {
alert('Something Went Wrong')
}
});
})
})
</script>
</body>
</html>
Now add following namespaces in code behind

C# Code


using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Web.Services;
using System.Web.UI.WebControls;
Once we add namespaces need write the code like as shown below


public static string strcon = "Data Source=SureshDasari;Initial Catalog=MySampleDB;Integrated Security=true";
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindCountries();
}
}
public void BindCountries()
{
String strQuery = "select CountryID,CountryName from Country";
using (SqlConnection con = new SqlConnection(strcon))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
con.Open();
ddlcountries.DataSource = cmd.ExecuteReader();
ddlcountries.DataTextField = "CountryName";
ddlcountries.DataValueField = "CountryID";
ddlcountries.DataBind();
ddlcountries.Items.Insert(0, new ListItem("Select Country", "0"));
con.Close();
}
}
}
[WebMethod]
public static string BindStates(string country)
{
StringWriter builder = new StringWriter();
String strQuery = "select StateID,StateName from State where CountryID=@CountryID";
DataSet ds = new DataSet();
using (SqlConnection con = new SqlConnection(strcon))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Parameters.AddWithValue("@countryid", country);
cmd.Connection = con;
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
con.Close();
}
}
DataTable dt = ds.Tables[0];
builder.WriteLine("[");
if (dt.Rows.Count > 0)
{
builder.WriteLine("{\"optionDisplay\":\"Select State\",");
builder.WriteLine("\"optionValue\":\"0\"},");
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
builder.WriteLine("{\"optionDisplay\":\"" + dt.Rows[i]["StateName"] + "\",");
builder.WriteLine("\"optionValue\":\"" + dt.Rows[i]["StateID"]+ "\"},");
}
}
else
{
builder.WriteLine("{\"optionDisplay\":\"Select State\",");
builder.WriteLine("\"optionValue\":\"0\"},");
}
string returnjson = builder.ToString().Substring(0, builder.ToString().Length - 3);
returnjson = returnjson + "]";
return returnjson.Replace("\r", "").Replace("\n", "");
}

[WebMethod]
public static string BindRegion(string state)
{
StringWriter builder = new StringWriter();
String strQuery = "select RegionID, RegionName from Region where StateID=@StateID";
DataSet ds = new DataSet();
using (SqlConnection con = new SqlConnection(strcon))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Parameters.AddWithValue("@StateID", state);
cmd.Connection = con;
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
con.Close();
}
}
DataTable dt = ds.Tables[0];
builder.WriteLine("[");
if (dt.Rows.Count > 0)
{
builder.WriteLine("{\"optionDisplay\":\"Select Region\",");
builder.WriteLine("\"optionValue\":\"0\"},");
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
builder.WriteLine("{\"optionDisplay\":\"" + dt.Rows[i]["RegionName"] + "\",");
builder.WriteLine("\"optionValue\":\"" + dt.Rows[i]["RegionID"] + "\"},");
}
}
else
{
builder.WriteLine("{\"optionDisplay\":\"Select Region\",");
builder.WriteLine("\"optionValue\":\"0\"},");
}
string returnjson = builder.ToString().Substring(0, builder.ToString().Length - 3);
returnjson = returnjson + "]";
return returnjson.Replace("\r", "").Replace("\n", "");
}
VB.NET Code


Imports System.Data
Imports System.Data.SqlClient
Imports System.IO
Imports System.Web.Services
Imports System.Web.UI.WebControls

Partial Class VBCode
Inherits System.Web.UI.Page
Public Shared strcon As String = "Data Source=SureshDasari;Initial Catalog=MySampleDB;Integrated Security=true"
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load

If Not IsPostBack Then
BindCountries()
End If
End Sub
Public Sub BindCountries()
Dim strQuery As [String] = "select CountryID,CountryName from Country"
Using con As New SqlConnection(strcon)
Using cmd As New SqlCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = strQuery
cmd.Connection = con
con.Open()
ddlcountries.DataSource = cmd.ExecuteReader()
ddlcountries.DataTextField = "CountryName"
ddlcountries.DataValueField = "CountryID"
ddlcountries.DataBind()
ddlcountries.Items.Insert(0, New ListItem("Select Country", "0"))
con.Close()
End Using
End Using
End Sub
<WebMethod()> _
Public Shared Function BindStates(ByVal country As String) As String
Dim builder As New StringWriter()
Dim strQuery As [String] = "select StateID,StateName from State where CountryID=@CountryID"
Dim ds As New DataSet()
Using con As New SqlConnection(strcon)
Using cmd As New SqlCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = strQuery
cmd.Parameters.AddWithValue("@countryid", country)
cmd.Connection = con
con.Open()
Dim da As New SqlDataAdapter(cmd)
da.Fill(ds)
con.Close()
End Using
End Using
Dim dt As DataTable = ds.Tables(0)
builder.WriteLine("[")
If dt.Rows.Count > 0 Then
builder.WriteLine("{""optionDisplay"":""Select State"",")
builder.WriteLine("""optionValue"":""0""},")
For i As Integer = 0 To dt.Rows.Count - 1
builder.WriteLine("{""optionDisplay"":""" & Convert.ToString(dt.Rows(i)("StateName")) & """,")
builder.WriteLine("""optionValue"":""" & Convert.ToString(dt.Rows(i)("StateID")) & """},")
Next
Else
builder.WriteLine("{""optionDisplay"":""Select State"",")
builder.WriteLine("""optionValue"":""0""},")
End If
Dim returnjson As String = builder.ToString().Substring(0, builder.ToString().Length - 3)
returnjson = returnjson & "]"
Return returnjson.Replace(vbCr, "").Replace(vbLf, "")
End Function

<WebMethod()> _
Public Shared Function BindRegion(ByVal state As String) As String
Dim builder As New StringWriter()
Dim strQuery As [String] = "select RegionID, RegionName from Region where StateID=@StateID"
Dim ds As New DataSet()
Using con As New SqlConnection(strcon)
Using cmd As New SqlCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = strQuery
cmd.Parameters.AddWithValue("@StateID", state)
cmd.Connection = con
con.Open()
Dim da As New SqlDataAdapter(cmd)
da.Fill(ds)
con.Close()
End Using
End Using
Dim dt As DataTable = ds.Tables(0)
builder.WriteLine("[")
If dt.Rows.Count > 0 Then
builder.WriteLine("{""optionDisplay"":""Select Region"",")
builder.WriteLine("""optionValue"":""0""},")
For i As Integer = 0 To dt.Rows.Count - 1
builder.WriteLine("{""optionDisplay"":""" & Convert.ToString(dt.Rows(i)("RegionName")) & """,")
builder.WriteLine("""optionValue"":""" & Convert.ToString(dt.Rows(i)("RegionID")) & """},")
Next
Else
builder.WriteLine("{""optionDisplay"":""Select Region"",")
builder.WriteLine("""optionValue"":""0""},")
End If
Dim returnjson As String = builder.ToString().Substring(0, builder.ToString().Length - 3)
returnjson = returnjson & "]"
Return returnjson.Replace(vbCr, "").Replace(vbLf, "")
End Function
End Class
Demo


Download sample code attached

If you enjoyed this post, please support the blog below. It's FREE!

Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email

17 comments :

Kedar Kumar Nayak said...

Sorry, Suresh. Country Name is Bound perfectly. But while choosing a country from the list, it is showing error, "Something Went Wrong". Please solve this.

Anonymous said...

Thanks

Anonymous said...

Really Nice

Apple said...

Couldn't download the attached code.

Sivas kangalı said...

Thanks...

Jitendra Gangwar said...

hello suresh there is a problem and also i could not download attached file...Please modified it

NIK said...

Hello Suresh,
When Implemented your code, I am getting an error while loading the page with the 3 drop-down:
Microsoft JScript runtime error: 'Sys.Extended.UI' is null or not an object

I am using Visual Studio 2008 and .NET Framework 3.5
Have downloaded Ajax Toolkit version 3.5

Can you please point out the error, what should I Try to load the page correctly.

devtools korzh.com said...

Thank you!

Anonymous said...

Hello Suresh,
Successfully implemented your code and its working fine. But now when i am saving the record on button click. binded dropdownlist is becoming empty.

Kindly tell me where i am going wrong.

Thanks

Mihir

Faisal Thayyil said...

Very good

Faisal Thayyil said...
This comment has been removed by the author.
Faisal Thayyil said...

When I dont get from any where this site will give always hope

Anonymous said...

Hi Suresh,

I have implemented same code in MS Visual Studio 2010 Express but getting error 'Something Went Wrong' as display in alert after selecting the country from Country dropdown.... Can you plz help me to identify the issue?.

Anonymous said...

Hi Suresh , It's really great work by you but i am getting error when i click on submit button error description as follows:-
"Invalid postback or callback argument. Event validation is enabled using in configuration or <%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation."

Anonymous said...

Hi Suresh,

When i am running the above code, On selection of an item into country dropdown doesnt fill states in the states dropdown. It is showing the error "Some thing went wrong". Plz suggest

Rama Gopala Krishna Murthy said...

When i am running the above code, On selection of an item into country dropdown doesnt fill states in the states dropdown. It is showing the error "Some thing went wrong". Plz help me suresh.

balaji said...

String strQuery = "select StateID,StateName from State where CountryID=@CountryID";

what is this?i didnt get this one..alredy state table is there,but what is CountryId?

Give your Valuable Comments

Other Related Posts

© 2010-2012 Aspdotnet-Suresh.com. All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.