测试数据
create table Country(
cntID int not null,
cntName nvarchar(10) not null
)
create table City(
citID int not null,
cntID int not null,
citName nvarchar(10) not null
)
insert into Country
select 1,N'中国'
union select 2,N'美国'
insert into City
select 1,1,N'北京'
union select 2,1,N'上海'
union select 3,2,N'纽约'
union select 4,2,N'华盛顿'
前台代码
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="scriptmanager" runat="server" EnablePageMethods="true"></asp:ScriptManager>
<%--使用PageMethods 方法需要加入asp:ScriptManager--%>
<script type="text/javascript">
$(function () {
$('#ddl_Country').change(ddlCountryChange);
});
function ddlCountryChange() {
var $cnt = $('#ddl_Country');
PageMethods.ddl_CityDataBind($cnt.val(), getCnt_callback)
}
function getCnt_callback(data) {
var $cty = $('#ddl_City');
$cty.empty();
if (data == '') return;
$("" + data).appendTo($cty);
}
</script>
<div>
<asp:DropDownList ID="ddl_Country" runat="server" Width="100px" ></asp:DropDownList>
<asp:DropDownList ID="ddl_City" runat="server" Width="100px"></asp:DropDownList>
</div>
</form>
</body>
后台代码
//使用DataClass连接数据库,用于编写linq语句
private static DataClasses1DataContext table = new DataClasses1DataContext();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
ddlBind();
}
#region ddl bind
private void ddlBind()
{
ddl_CountryDataBind();
ddl_CityDataBind();
}
// ddl_Country databind
private void ddl_CountryDataBind()
{
var cntBind = from cnt in table.Countries
select new { cnt.cntID, cnt.cntName };
ddl_Country.DataSource = cntBind;
ddl_Country.DataTextField = "cntName";
ddl_Country.DataValueField = "cntID";
ddl_Country.DataBind();
ddl_Country.Items.Insert(0, new ListItem("请选择", ""));
}
//ddl_City databind
private void ddl_CityDataBind()
{
var citBind = from cty in table.Cities
select new { cty.citID, cty.citName };
ddl_City.DataSource = citBind;
ddl_City.DataTextField = "citName";
ddl_City.DataValueField = "citID";
ddl_City.DataBind();
ddl_City.Items.Insert(0, new ListItem("请选择", ""));
}
[WebMethod]
public static string ddl_CityDataBind(string ctID)
{
string dtbind = string.Empty;
dtbind = "<option value=''>请选择</option>";
if (string.IsNullOrEmpty(ctID))
return dtbind;
//linq 语句,改语句等价于
// select cty.citID,cty.citName from City cty where cty.cntID=ctID
var citBind = from cty in table.Cities
where cty.cntID == Convert.ToInt32(ctID)
select new { cty.citID, cty.citName };
foreach (var cty in citBind)
{
dtbind = dtbind + "<option value='" + cty.citID + "'>" + cty.citName + "</option>";
}
return dtbind;
}
#endregion