无刷新DropdownList联动
一、数据库设计:
字段名 数据类型 说明
ClassID 自动编号 类编号
ClassName varchar(8) 类名
UpClassID int(4) 上级类编号
ClassLevel int(4) 类级别,1为大类,2为小类
二、设计步骤:
1、首先,我们新建一个页面DropTest.aspx,在其中放入两个DropDownList控件:
DropDownList1和DropDownList2,其完整代码如下:<%@ Page language="c#" Codebehind="DropTest.aspx.cs" AutoEventWireup="false" Inherits="studyWEB.DropTest" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>WebForm2</title>
<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
<meta content="C#" name="CODE_LANGUAGE">
<meta content="JavaScript" name="vs_defaultClientScript">
<meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
<script>
function load(ClassID){ //ClassID为接收传递的大类编号
var drp2 = document.getElementById("DropDownList2");
function RemoveAll(oElem) { //清除DropDownList2的所有项
var i = 0;
for (i = oElem.length; i >= 0; i--){
oElem.options.remove(i);
}
}
RemoveAll(drp2)
//新建一请求与XML文档
var oHttpReq = new ActiveXObject("MSXML2.XMLHTTP");
var oDoc = new ActiveXObject("MSXML2.DOMDocument");
//调用读取小类数据的页面,将大类
// 编号值传递过去
oHttpReq.send("");
result = oHttpReq.responseText;
oDoc.loadXML(result);
items1 = oDoc.selectNodes("//CLASSNAME/Table/ClassName");
//读取所有请求大类所属小类的类名
items2 = oDoc.selectNodes("//CLASSNAME/Table/ClassID");
//读取所有请求大类所属小类的编号
var itemsLength=items1.length;
for(i=0;i<itemsLength;i++)
//将小类的类名和编号赋予DropDownList2
{
var newOption = document.createElement("OPTION");
newOption.text=items1[i].text;
newOption.value=items2[i].text;
drp2.options.add(newOption);
}
}
</script>
</HEAD>
<body MS_POSITIONING="flowLayout">
<form id="Form1" method="post" runat="server">
<asp:DropDownList id="DropDownList1" runat="server"></asp:DropDownList>
<asp:DropDownList id="DropDownList2" runat="server"></asp:DropDownList>
<asp:TextBox id="TH" runat="server" BorderStyle="None" ForeColor="White" BorderColor="White"></asp:TextBox>
<asp:Label id="Label1" runat="server"></asp:Label>
<asp:Button id="Button1" runat="server" Text="Button"></asp:Button>
</form>
</body>
</HTML>
该页面的后台文件(DropDownList1.aspx.cs)中Page_Load内的代码如下:
if(!this.IsPostBack)
{
SqlConnection con = new SqlConnection("server=localhost;database=gswebDB;uid=sa;pwd=;");
SqlDataAdapter da = new SqlDataAdapter("select ClassName,ClassID from classname where ClassLevel=1",con);
DataSet ds = new DataSet();
da.Fill(ds);
this.DropDownList1.DataSource=ds.Tables[0].DefaultView;
this.DropDownList1.DataTextField = "ClassName";
this.DropDownList1.DataValueField = "ClassID";
this.DropDownList1.DataBind();
this.DropDownList1.Attributes.Add("onchange","load(this.options[this.selectedIndex].value)");
//将ClassID作为参数传递给脚本函数load(ClassID),
如果要传递的是ClassName,应将value改为innerText,但如果大类为中文,
则调用小类时出现无法显示的问题
// this.DropDownList2.Attributes.Add("onChange",
"javascript:document.Form1.TH.value=this.options[this.selectedIndex].value;");
//读取DropDownList2的值,将其赋给一个TextBox控件TH,以获取DropDownList2的值,为获取DropDownList2的值.