asp.net实现无刷新DropDownList联动控件

ASP.NET给我们带了了事件模型的编程机制,这使得我们将所有的任务都放在服务器上执行哪怕是一个小小变动,其实这到不是什么问题,可是有一点我们无法忍受,如果我们改变某一个输入框中的内容页面要刷新,改变DropDownlist的选择项需要更新另一个Dropdownlist需要刷新,真是郁闷。        下面我将描述一种原始的方法,之所以说它原是是因为这种方法在ASP.NET之前就已经有了,我想这两者之间的关系我不必详细描述,我们今天要说的是如何不刷新页面更新DropDownList,该方法旨在抛砖引玉,其实使用该方法可以实现许多不刷新网页就和后台交互的应用,好了废话就不说了,看看我们的例子吧,首先我们需要一个放置两个DropDownList的页面,页面的代码如下:
<%@ Page language="c#" Codebehind="Example.aspx.cs" AutoEventWireup="false" Inherits="Webs.other.Example" %>
<HTML>
<HEAD>
<title>Example</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5";>
<script>
function load(state){
var drp2 = document.getElementById("DropDownList2");
for (i = drp2.length; i >= 0; i--){
drp2.options.remove(i);
}

var oHttpReq = new ActiveXObject("MSXML2.XMLHTTP");
var oDoc = new ActiveXObject("MSXML2.DOMDocument");

oHttpReq.open("POST", "getData.aspx?state="+state, false);
oHttpReq.send("");
result = oHttpReq.responseText;
oDoc.loadXML(result);
items1 = oDoc.selectNodes("//CITY/Table/Id");
items2 = oDoc.selectNodes("//CITY/Table/shiname");

var itemsLength=items1.length;
  for(i=0;i<itemsLength;i++)

//将小类的类名和编号赋予DropDownList2
  {
  var newOption = document.createElement("OPTION");
  newOption.text=items2[i].text;
  newOption.value=items1[i].text;
  drp2.options.add(newOption);
  }
}
window.onload = function(){load('1');}

</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"></asp:TextBox>
<asp:Button id="Button1" runat="server" Text="Button"></asp:Button>
</form>
</body>
</HTML>

上面的页面中有两个DropDownList和一段js脚本,该脚本可以直接写在页面也可以写在后台在Regeist到页面上(后者更灵活一些)该页的后台代码如下所示,
cs源文件:

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

namespace Webs.other
{
/// <summary>
/// Example 的摘要说明。
/// </summary>
public class Example : System.Web.UI.Page
{
 protected System.Web.UI.WebControls.DropDownList DropDownList1;
 protected System.Web.UI.WebControls.TextBox TH;
 protected System.Web.UI.WebControls.Button Button1;
 protected System.Web.UI.WebControls.DropDownList DropDownList2;

 private void Page_Load(object sender, System.EventArgs e)
 {
  // 在此处放置用户代码以初始化页面
  if(!this.IsPostBack)
  {
   // 建立数据源加载第一个DropDownList,也可以默认加载第二个
   SqlConnection con = new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings.Get("connStr1"));
   SqlDataAdapter da = new SqlDataAdapter("select Id,shengname from Province",con);
   DataSet ds = new DataSet();
   da.Fill(ds);
   this.DropDownList1.DataSource = ds;
   this.DropDownList1.DataTextField = "shengname";
   this.DropDownList1.DataValueField = "Id";
   this.DropDownList1.DataBind();
   // 这里是绑定客户端事件,当第一个DropDownList的选项改变时激发下面的事件onchange,这个事件将调用一个客户端方法load()
   this.DropDownList1.Attributes.Add("onchange","load(this.options[this.selectedIndex].value)");
  }
 }

 #region Web Form Designer generated code
 override protected void OnInit(EventArgs e)
 {
  //
  // CODEGEN:该调用是 ASP.NET Web 窗体设计器所必需的。
  //
  InitializeComponent();
  base.OnInit(e);
 }
 
 /// <summary>
 /// 设计器支持所需的方法 - 不要使用代码编辑器修改
 /// 此方法的内容。
 /// </summary>
 private void InitializeComponent()
 {    
  this.Button1.Click += new System.EventHandler(this.Button1_Click);
  this.Load += new System.EventHandler(this.Page_Load);

 }
 #endregion

 private void Button1_Click(object sender, System.EventArgs e)
 {
  TH.Text=this.Request.Form["DropDownList2"].ToString();
 }
}
}
 在上面的代码中我们做了两件事情:1、帮定其中一个DropDownList(你也可以同时绑定两个)。2、指定该控件的客户端脚本。下面我们详细介绍一下上面的js代码,首先得到页面上要联动的DorpDownList对象,将他的Options清空,再创建两个客户端对象oHttpReq和oDoc对象,其中一个负责发送请求另一个负责得到响应结果,我们将用户选择的State发送到名为WebForm6.aspx的页面,该页面将处理这个请求并返回一个响应,该响应的结果是一个XML文件,稍候介绍WebForm6.aspx里面的代码。我们将返回的结果使用loadXML方法Load到oDoc对象里面,然后就可以使用selectNodes方法得到所有的city节点,接着循环这些节点在客户端创建Option对象,最后将这些Option对象Add到DropDwonList2里面去。   
getdata源文件


using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Xml;
using System.Configuration;
using System.Text;

namespace Webs.other
{
/// <summary>
/// GetData 的摘要说明。
/// </summary>
public class GetData : System.Web.UI.Page
{
 private void Page_Load(object sender, System.EventArgs e)
 {
  // 在此处放置用户代码以初始化页面
  //Response.Write(Request["state"]);
  int shengNo=int.Parse(Request["state"].ToString());  
  SqlConnection con = new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings.Get("connStr1"));
  SqlDataAdapter da = new SqlDataAdapter("select Id,shiname from City where Shengid='"+shengNo+"'",con);
  DataSet ds = new DataSet("CITY");
  da.Fill(ds);

  XmlTextWriter writer = new XmlTextWriter(Response.OutputStream,Encoding.UTF8);
  writer.Formatting = Formatting.Indented;
  writer.Indentation = 4;
  writer.IndentChar = ' ';
  writer.WriteStartDocument();
  ds.WriteXml(writer);
  writer.Flush();
  Response.End();
  writer.Close();  
 }

 #region Web Form Designer generated code
 override protected void OnInit(EventArgs e)
 {
  //
  // CODEGEN:该调用是 ASP.NET Web 窗体设计器所必需的。
  //
  InitializeComponent();
  base.OnInit(e);
 }
 
 /// <summary>
 /// 设计器支持所需的方法 - 不要使用代码编辑器修改
 /// 此方法的内容。
 /// </summary>
 private void InitializeComponent()
 {    
  this.Load += new System.EventHandler(this.Page_Load);
 }
 #endregion
}
}
 
原文地址:https://www.cnblogs.com/ruanbl/p/773939.html