Microsoft AjaxToolkits 20. CascadingDropDown控件

CascadingDropDown控件用于级连下拉列表的选择,当没有选择第一级下接列表时,第二级是不可选的(从服务器获得数据然后再显示数据)。

属性列表:
TargetControlID:对应的下拉框表控件的ID
Category:当前下拉列表的类型
PromptText:当下拉列表中无数据或没有选择数据时给用户的提示
LoadingText:加载下拉列表数据时的提示
ServicePath:下拉列表获取数据所要的WEB服务路径
ServiceMethod:WEB服务方法
ParentControlID:控制此下拉列表控件的父级控件
SelectedValue:默认的选择值

常见问题和使用技巧
常见问题:在中了联动下拉列表组之后,页面的回送会引发服务器端掷出“Invalid postback or callback argument”的异常,服务器端也无法取得每个下拉框表中的条目?
使用技巧:我们可以在web.config中加入<pages enableEventValidation="true" />或者在当前页面注册<%@ Page Language="C#" EnableEventValidation="false" %>这样会导至应该程序的安全性。
常见问题:如何设置联动下拉列表组中被选中的项目?
使用技巧:DropDownList1.SelectedValue="China";或者:
<ajaxToolkit:CascadingDropDown ID="ccdCity" TargetControlID="ddlCity" Category="City" PromptText="请选择城市" LoadingText="城市加载中..." ServicePath="CityService.asmx" ServiceMethod="GetCitiesForProvince" ParentControlID="ddlProvince" runat="server" SelectedValue="beijing" />


实例解析一、实现三级连动

1.前台UI
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
</div>
<table>
<tr>
<td style="width: 100px">学校:</td>
<td style="width: 100px"><asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList></td>
<td style="width: 100px">
<ajaxToolkit:CascadingDropDown ID="CascadingDropDown1" runat="server" Category="schoolname"
LoadingText="正在加载学校" PromptText="请选择学校" ServiceMethod="GetSchool" TargetControlID="DropDownList1" ServicePath="PersonDBservice.asmx">
</ajaxToolkit:CascadingDropDown>
</td>
</tr>
<tr>
<td style="width: 100px">部门:</td>
<td style="width: 100px"><asp:DropDownList ID="DropDownList2" runat="server"></asp:DropDownList></td>
<td style="width: 100px">
<ajaxToolkit:CascadingDropDown ID="CascadingDropDown2" runat="server" Category="departname"
LoadingText="正在加载部门" PromptText="请选择部门" ServiceMethod="GetDepartsForSchool" TargetControlID="DropDownList2" ServicePath="PersonDBservice.asmx">
</ajaxToolkit:CascadingDropDown>
</td>
</tr>
<tr>
<td style="width: 100px">成员</td>
<td style="width: 100px"><asp:DropDownList ID="DropDownList3" runat="server" OnSelectedIndexChanged="DropDownList3_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList></td>
<td style="width: 100px">
<ajaxToolkit:CascadingDropDown ID="CascadingDropDown3" runat="server" Category="personname"
LoadingText="正在加载人员" PromptText="请选择人员" ServiceMethod="GetPersonsForDepart" TargetControlID="DropDownList3" ServicePath="PersonDBservice.asmx">
</ajaxToolkit:CascadingDropDown>
</td>
</tr>
</table>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="DropDownList3" EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
</form>
</body>
2.后台CS
protected void DropDownList3_SelectedIndexChanged(object sender, EventArgs e)
{
string person = DropDownList1.SelectedItem.Text + "学校" + DropDownList2.SelectedItem.Text + "部门的" + DropDownList3.SelectedItem.Text;
Label1.Text = person;
}
3.PersonDBservice.cs WEB服务文件

using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data.SqlClient;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using AjaxControlToolkit;


/// <summary>
/// PersonDBservice 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class PersonDBservice : System.Web.Services.WebService {

public PersonDBservice () {

//如果使用设计的组件,请取消注释以下行
//InitializeComponent();
}

[WebMethod]
public string HelloWorld() {
return "Hello World";
}

public DataTable getSchoolTable()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SqlServerConStr"].ToString());
SqlDataAdapter sdr = new SqlDataAdapter("select schoolid,schoolname from schoolinfo", con);
DataSet ds = new DataSet();
sdr.Fill(ds);
return ds.Tables[0];
}

public DataTable getDepartTable(int schoolid)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SqlServerConStr"].ToString());
SqlDataAdapter sdr = new SqlDataAdapter("select departid,departname from departinfo where schoolid="+schoolid.ToString(), con);
DataSet ds = new DataSet();
sdr.Fill(ds);
return ds.Tables[0];
}

public DataTable getSchoolTable(int departid)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SqlServerConStr"].ToString());
SqlDataAdapter sdr = new SqlDataAdapter("select personid,personname from personinfo where personid="+departid.ToString(), con);
DataSet ds = new DataSet();
sdr.Fill(ds);
return ds.Tables[0];
}

[WebMethod]
public CascadingDropDownNameValue[] GetSchool(string knownCategoryValue, string category)
{
List<CascadingDropDownNameValue> values = new List<CascadingDropDownNameValue>();
DataTable schools = getSchoolTable();
foreach (DataRow dr in schools.Rows)
{
string school = (string)dr["schoolname"];
int schoolid=(int)dr["schoolid"];
values.Add(new CascadingDropDownNameValue(school,schoolid.ToString()));

}
return values.ToArray();
}

[WebMethod]
public CascadingDropDownNameValue[] GetDepartsForSchool(string knownCategoryValue, string category)
{
StringDictionary kv = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValue);
int schoolId;
if (!kv.ContainsKey("departname") || !Int32.TryParse(kv["departname"], out schoolId))
{
return null;
}
DataTable departs = getDepartTable(schoolId);

List<CascadingDropDownNameValue> values = new List<CascadingDropDownNameValue>();
foreach (DataRow dr in departs.Rows)
{
values.Add(new CascadingDropDownNameValue((string)dr["departname"], dr["departid"].ToString()));

}
return values.ToArray();
}

[WebMethod]
public CascadingDropDownNameValue[] GetPersonsForDepart(string knownCategoryValue, string category)
{
StringDictionary kv = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValue);
int departind;
if (!kv.ContainsKey("personname") || !Int32.TryParse(kv["personname"], out departind))
{
return null;
}
DataTable persons = getDepartTable(departind);
List<CascadingDropDownNameValue> values = new List<CascadingDropDownNameValue>();
foreach (DataRow dr in persons.Rows)
{
values.Add(new CascadingDropDownNameValue((string)dr["personname"], dr["personid"].ToString()));

}
return values.ToArray();
}
}
实例解析二、实现静态三级连动

1.前台UI
<head runat="server">
<title>CascadingDropDown Demo</title>
<link href="StyleSheet.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form id="form1" runat="server">
<asp:scriptmanager id="sm" runat="server"></asp:scriptmanager>
请选择您所在的城市:
<asp:DropDownList ID="ddlCountry" runat="server"></asp:DropDownList>
<asp:DropDownList ID="ddlProvince" runat="server"></asp:DropDownList>
<asp:DropDownList ID="ddlCity" runat="server"></asp:DropDownList>
<ajaxToolkit:CascadingDropDown ID="ccdCountry" TargetControlID="ddlCountry" Category="Country"
PromptText="请选择国家" LoadingText="国家加载中..." ServicePath="CityService.asmx" ServiceMethod="GetCountries"
runat="server" />
<ajaxToolkit:CascadingDropDown ID="ccdProvince" TargetControlID="ddlProvince" Category="Province"
PromptText="请选择省份" LoadingText="省份加载中..." ServicePath="CityService.asmx" ServiceMethod="GetProvincesForCountry"
ParentControlID="ddlCountry" runat="server" />
<ajaxToolkit:CascadingDropDown ID="ccdCity" TargetControlID="ddlCity" Category="City"
PromptText="请选择城市" LoadingText="城市加载中..." ServicePath="CityService.asmx" ServiceMethod="GetCitiesForProvince"
ParentControlID="ddlProvince" runat="server" />
</form>
</body

2.WEB服务
<%@ WebService Language="C#" class="CityService" %>

using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Collections.Generic;
using System.Collections.Specialized;
using AjaxControlToolkit;

[WebService(Namespace = "http://www.dflying.net/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService()]
public class CityService : System.Web.Services.WebService
{

[WebMethod]
public CascadingDropDownNameValue[] GetCountries(string knownCategoryValues, string category)
{
List<CascadingDropDownNameValue> countryList = new List<CascadingDropDownNameValue>();

// 在真实程序中一般从数据库中读取,这里仅仅是模拟
countryList.Add(new CascadingDropDownNameValue("中国", "china"));
countryList.Add(new CascadingDropDownNameValue("其他", "other"));

return countryList.ToArray();
}

[WebMethod]
public CascadingDropDownNameValue[] GetProvincesForCountry(string knownCategoryValues, string category)
{
StringDictionary kv = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
// 只模拟提供中国的省份
if (kv["Country"] != "china")
return null;

List<CascadingDropDownNameValue> provinceList = new List<CascadingDropDownNameValue>();
provinceList.Add(new CascadingDropDownNameValue("辽宁", "liaoning"));
provinceList.Add(new CascadingDropDownNameValue("上海", "shanghai"));
provinceList.Add(new CascadingDropDownNameValue("北京", "beijing"));
return provinceList.ToArray();
}

[WebMethod]
public CascadingDropDownNameValue[] GetCitiesForProvince(string knownCategoryValues, string category)
{
StringDictionary kv = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);

// 只模拟提供辽宁省内的城市
if (kv["Province"] != "liaoning")
return null;

List<CascadingDropDownNameValue> cityList = new List<CascadingDropDownNameValue>();
cityList.Add(new CascadingDropDownNameValue("沈阳", "shenyang"));
cityList.Add(new CascadingDropDownNameValue("大连", "dalian"));

return cityList.ToArray();
}

}
效果图:

实例解析、动态添加数据库
<script type="text/javascript">
function validateSkills(sender, args)
{
if (args.Value == "Input skills...")
{
args.IsValid = false;
}
}
</script>
<table style="width: 100%;">
<tr>
<td align="left" style="padding-left: 30px;"><asp:DropDownList ID="ddlCountry" Runat="server" ></asp:DropDownList></td>
</tr>
<tr>
<td align="left" style="padding-left: 30px;"><asp:DropDownList ID="ddlState" Runat="server"></asp:DropDownList></td>
</tr>
</table>
<ajaxToolkit:CascadingDropDown ID="cddCountry" runat="server"
TargetControlID="ddlCountry"
Category="Country"
PromptText="Please Choose a Country"
LoadingText="Loading Countries..."
ServicePath="../LocationService.asmx"
ServiceMethod="GetCountries" />
<ajaxToolkit:CascadingDropDown ID="cddCity" runat="server"
TargetControlID="ddlState"
Category="City"
PromptText="Please Choose a State"
LoadingText="Loading States..."
ServicePath="../LocationService.asmx"
ServiceMethod="GetStatesForCountry"
ParentControlID="ddlCountry" />

2.web服务
sing System.Data;
using System.Collections.Generic;
using System.Collections.Specialized;
using AjaxControlToolkit;
using JobSiteStarterKit.DAL;
using JobSiteStarterKit.BOL;
/// <summary>
/// Summary description for LocationService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService()]
public class LocationService : System.Web.Services.WebService
{

[WebMethod]
public CascadingDropDownNameValue[] GetCountries(string knownCategoryValues, string category)
{
List<CascadingDropDownNameValue> countryList = new List<CascadingDropDownNameValue>();

DataSet dsCountry = Country.GetCountries();
foreach (DataRow row in dsCountry.Tables[0].Rows)
{
countryList.Add(new CascadingDropDownNameValue(row["CountryName"].ToString(), row["CountryID"].ToString()));
}

return countryList.ToArray();
}

[WebMethod]
public CascadingDropDownNameValue[] GetStatesForCountry(string knownCategoryValues, string category)
{
StringDictionary kv = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);

List<CascadingDropDownNameValue> stateList = new List<CascadingDropDownNameValue>();

DataSet dsState = State.GetStates(int.Parse(kv["Country"]));
foreach (DataRow row in dsState.Tables[0].Rows)
{
stateList.Add(new CascadingDropDownNameValue(row["StateName"].ToString(), row["StateID"].ToString()));
}

return stateList.ToArray();
}

}

posted @ 2012-05-24 23:06  烧点饭  阅读(159)  评论(0编辑  收藏  举报