CascadingDropDown Sample - Ajax Control Toolkit
Step 1 : aspx page
<table>
<tr>
<td style="width: 80px">Country:
</td>
<td>
<asp:DropDownList ID="ddlCountries" runat="server" Width="150">
</asp:DropDownList>
<cc1:CascadingDropDown ID="cdlCountries" TargetControlID="ddlCountries" PromptText="Select Country"
PromptValue="" ServicePath="myservices.asmx" ServiceMethod="GetCountries" runat="server"
Category="CountryId" LoadingText="Loading..." />
</td>
</tr>
<tr>
<td>State:
</td>
<td>
<asp:DropDownList ID="ddlStates" runat="server" Width="150">
</asp:DropDownList>
<cc1:CascadingDropDown ID="cdlStates" TargetControlID="ddlStates" PromptText="Select State"
PromptValue="-1" ServicePath="myservices.asmx" ServiceMethod="GetStates" runat="server"
Category="StateId" ParentControlID="ddlCountries" LoadingText="Loading..." />
</td>
</tr>
<tr>
<td>City:
</td>
<td>
<asp:DropDownList ID="ddlCities" runat="server" Width="150">
</asp:DropDownList>
<cc1:CascadingDropDown ID="cdlCities" TargetControlID="ddlCities" PromptText="Select City"
PromptValue="-1" ServicePath="myservices.asmx" ServiceMethod="GetCities" runat="server"
Category="CityId" ParentControlID="ddlStates" LoadingText="Loading..." />
</td>
</tr>
</table>
step 2 : service page
[WebMethod]
public CascadingDropDownNameValue[] GetCountries(string knownCategoryValues)
{
string query = "SELECT CountryName, CountryId FROM Countries";
List<CascadingDropDownNameValue> countries = GetData(query);
return countries.ToArray();
}
[WebMethod]
public CascadingDropDownNameValue[] GetStates(string knownCategoryValues)
{
string country = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues)["CountryId"];
string query = string.Format("SELECT StateName, StateId FROM States WHERE CountryId = {0}", country);
List<CascadingDropDownNameValue> states = GetData(query);
return states.ToArray();
}
[WebMethod]
public CascadingDropDownNameValue[] GetCities(string knownCategoryValues)
{
string state = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues)["StateId"];
string query = string.Format("SELECT CityName, CityId FROM Cities WHERE StateId = {0}", state);
List<CascadingDropDownNameValue> cities = GetData(query);
return cities.ToArray();
}
private List<CascadingDropDownNameValue> GetData(string query)
{
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
SqlCommand cmd = new SqlCommand(query);
List<CascadingDropDownNameValue> values = new List<CascadingDropDownNameValue>();
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
cmd.Connection = con;
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
values.Add(new CascadingDropDownNameValue
{
name = reader[0].ToString(),
value = reader[1].ToString()
});
}
reader.Close();
con.Close();
return values;
}
}
}
Comments
Post a Comment