Cascading dropdownlist Controls are those that depend on the selected value of each other dropdownlist. Here, when a value is selected on one dropdownlist, the depending dropdownlist is populated with another set of values.
A classic example of cascading dropdownlist is of Countries & Cities. One dropdownlist carries Country names and other carries the Cities of the Selected Country.
When a user selects a country (example United States) in the Country dropdownlist then the City dropdownlist is populated with the cities of United States (example NYC, Albany, San Francisco, Washington DC, Chicago, Los Angeles).
Create a new web form and name it index.aspx. Add 2 dropdownlist to this web form, one for categories and other for products. Also add a loading.gif image.
This image will tell users whenever the AJAX request is currently undergoing or not.
<asp:DropDownList ID="categoryDropDownList" runat="server" />
<asp:DropDownList ID="productDropDownList" runat="server" />
<div class="imageDiv">
<img src="loading.gif" />
</div>
Add the jQuery code for the change event of the category dropdownlist control. This event will be called whenever a user selects a category.
On selecting a category, the jQuery AJAX code inside this event will be executed. This code will call a C# function by the name of bindproduct() given on the .cs page, and passes the selected CategoryId value to it’s parameter.
$("#categoryDropDownList").change(function (e) {
$.ajax({
type: "POST",
url: "index.aspx/bindproduct",
contentType: "application/json; charset=utf-8",
data: '{"categoryId":"' + $(this).val() + '"}',
dataType: "json",
success: function (result, status, xhr) {
$("#productDropDownList").html(result.d);
},
error: function (xhr, status, error) {
alert("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
}
});
});
$(document).ajaxStart(function () {
$("img").show();
});
$(document).ajaxStop(function () {
$("img").hide();
});
I am calling the BindCategory() function in the Page_Load event. This function will populate the Category dropdownlist control with values from the database.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindCategory();
}
}
void BindCategory()
{
string query = "SELECT CATEGORYID,CATEGORYNAME FROM CATEGORIES";
SqlConnection conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
DataTable dataTable = new DataTable();
conn.ConnectionString = configurationManager.ConnectionStrings["CS"].ConnectionString;
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = query;
cmd.Connection = conn;
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();
sqlDataAdapter.SelectCommand = cmd;
sqlDataAdapter.Fill(dataTable);
categoryDropDownList.DataSource = dataTable;
categoryDropDownList.DataTextField = "CategoryName";
categoryDropDownList.DataValueField = "CategoryID";
categoryDropDownList.DataBind();
categoryDropDownList.Items.Insert(0, new ListItem("Select", "0"));
productDropDownList.Items.Insert(0, new ListItem("Select", "0"));
}
[WebMethod]
public static string bindproduct(string categoryId)
{
string query = "SELECT PRODUCTID,PRODUCTNAME FROM PRODUCTS WHERE CATEGORYID=" + categoryId;
SqlConnection conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
DataTable dataTable = new DataTable();
conn.ConnectionString = ConfigurationManager.ConnectionStrings["CS"].ConnectionString;
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = query;
cmd.Connection = conn;
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();
sqlDataAdapter.SelectCommand = cmd;
sqlDataAdapter.Fill(dataTable);
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append("<option value=\"0\">Select</option>");
foreach (DataRow dr in dataTable.Rows)
stringBuilder.Append("<option value=\"" + dr["ProductID"] + "\">" + dr["ProductName"] + "</option>");
return stringBuilder.ToString();
}
The most important part of the above code is the bindproduct() function. I have made it a WebMethod because it will be called from the jQuery AJAX code.
In this way the Product dropdownlist is populated and no Page PostBack happens.. The Download link is below: