</form>
 </body>
</HTML>

        上面的页面中有两个DropDownList和一段js脚本,该脚本可以直接写在页面也可以写在后台在Regeist到页面上(后者更灵活一些)该页的后台代码如下所示,在Page_Load里面写如下的代码:
 if(!this.IsPostBack){
  SqlConnection con = new SqlConnection("server=localhost;database=pubs;uid=sa;pwd=sa;");
  SqlDataAdapter da = new SqlDataAdapter("select state from authors group by state",con);
  DataSet ds = new DataSet();
  this.DropDownList1.DataTextField = "State";
  this.DropDownList1.DataValueField = "State";
  this.DropDownList1.DataBind();
  this.DropDownList1.Attributes.Add("onchange","load(this.options[this.selectedIndex].innerText)");
 }
       在上面的代码中我们做了两件事情:1、帮定其中一个DropDownList(你也可以同时绑定两个)。2、指定该控件的客户端脚本。下面我们详细介绍一下上面的js代码,首先得到页面上要联动的DorpDownList对象,将他的Options清空,再创建两个客户端对象oHttpReq和oDoc对象,其中一个负责发送请求另一个负责得到响应结果,我们将用户选择的State发送到名为WebForm6.aspx的页面,该页面将处理这个请求并返回一个响应,该响应的结果是一个XML文件,稍候介绍WebForm6.aspx里面的代码。我们将返回的结果使用loadXML方法Load到oDoc对象里面,然后就可以使用selectNodes方法得到所有的city节点,接着循环这些节点在客户端创建Option对象,最后将这些Option对象Add到DropDwonList2里面去。
        下面我们看看WebFowm6.aspx都做了些什么事情,该页面的HTML页面是一个除了包括<@Page>指令意外什么都没有的页面,后台的Page_Load代码如下:
 private void Page_Load(object sender, System.EventArgs e){
  // Put user code to initialize the page here
  if(this.Request["state"]!=null){
  string state = this.Request["state"].ToString();
  SqlConnection con = new SqlConnection("server=localhost;database=pubs;uid=sa;pwd=sa;");
  SqlDataAdapter da = new SqlDataAdapter("select city from authors where state = '"+state+"'",con);
  DataSet ds = new DataSet("CITY");
  da.Fill(ds);
  XmlTextWriter writer = new XmlTextWriter(Response.OutputStream, Response.ContentEncoding);
  writer.Formatting = Formatting.Indented;
  writer.Indentation = 4;
  writer.IndentChar = ' ';
  ds.WriteXml(writer);
  writer.Flush();
  Response.End();
  writer.Close();
 }
         该方法得到用户选择的state通过查询以后得到一个DataSet对象,使用该对象的WriteXML方法直接将内容写到Response.OutputStream里面然后传递到客户端,客户端的load方法通过result =oHttpReq.responseText;句话得到一个XML字符串,最后解析此串。

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-11-07
  • 2022-12-23
  • 2022-12-23
  • 2021-08-21
猜你喜欢
  • 2022-02-01
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案