DropDownList联动不刷新(二级)

这是一个简单的例子,在NorthWind数据库中建立了两张表,在后台用到了数据访问层,所以如果要测试,必须根据存储过程写一个方法去绑定DropDownList.
        界面如下:

1.表的创建:
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Type]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[Type]
GO

CREATE TABLE [dbo].[Type] (
 [ID] [int] IDENTITY (1, 1) NOT NULL ,
 [TypeName] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Info]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[Info]
GO

CREATE TABLE [dbo].[Info] (
 [ID] [int] IDENTITY (1, 1) NOT NULL ,
 [TypeID] [int] NULL ,
 [Info] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]
GO
创建表之后,可以在里面添加一些记录,注意Info表里的TypeID是Type表的外键,必须注意

2.用了数据访问层,用了存储过程,如下:
(1).SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

ALTER  PROC GetType
AS
--得到类型
SELECT * FROM TYPE

GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

(2).SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

ALTER  PROC GetInfoByTypeID
@TYPEID INT
AS
--得到类型的信息
SELECT ID,INFO FROM INFO WHERE TYPEID=@TYPEID

GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

前台:

<%@ Page language="c#" Codebehind="DropDownListRefur.aspx.cs" AutoEventWireup="false" Inherits="NetTest.DropDownListRefur" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
 <HEAD>
  <title>DropDownListRefur</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">
  <link href="Css/BasicLayout.css" rel="stylesheet" type="text/css">
 </HEAD>
 <body MS_POSITIONING="GridLayout">
  <form id="Form1" method="post" runat="server">
   <SCRIPT LANGUAGE="JavaScript">
    <!--
    //以XML求取数据
    function XmlPost(obj)
    {
      var svalue = obj.value;
      //alert(svalue);
      if(svalue=="请选择")
      {
       document.all("ddlInfo").length=0;
      }
      else
      {
       var webFileUrl = "DropDownListRefur.aspx?TypeID=" + svalue;
       var result = "";
       var xmlHttp = new ActiveXObject("MSXML2.XMLHTTP");
       xmlHttp.open("POST", webFileUrl, false);//使用XMLPOST方式
       xmlHttp.send("");//发送
       result = xmlHttp.responseText;//得到返回的结果
       
       if(result != "")
       {
         document.all("ddlInfo").length=0;//清空原来存在的
         var piArray = result.split(",");
         for(var i=0;i<piArray.length;i++)
         {
           var ary1 = piArray[i].toString().split("|");
           //alert(ary1[0].toString());
           //alert(ary1[1].toString());
           document.all("ddlInfo").options.add(new Option(ary1[0].toString(),ary1[1].toString()));
         }
       }
       else
       {
         alert(result);
       }
      }
    }
    //-->
   </SCRIPT>
   <table align="center" border="0" width="40%">
    <tr>
     <td align="right">
      <asp:DropDownList id="ddlType" runat="server" Width="124px"></asp:DropDownList></td>
     <td align="left">
      <asp:DropDownList id="ddlInfo" runat="server" Width="123px"></asp:DropDownList></td>
    </tr>
    <tr>
     <td colspan="2" align="center">
      <asp:Button id="btnSubmit" runat="server" Text="显示ddlInfo选中的编号" CssClass="redButtonCss"></asp:Button></td>
    </tr>
   </table>
  </form>
 </body>
</HTML>

后台:

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 DataBaseClass;
namespace NetTest
{
 /// <summary>
 /// DropDownListRefur 的摘要说明。
 /// </summary>
 public class DropDownListRefur : System.Web.UI.Page
 {
  protected System.Web.UI.WebControls.DropDownList ddlType;
  protected System.Web.UI.WebControls.DropDownList ddlInfo;
  protected System.Web.UI.WebControls.Button btnSubmit;
  private ClassDataGrid CDG=new ClassDataGrid();
  private void Page_Load(object sender, System.EventArgs e)
  {
   if(!IsPostBack)
   {
    RefurData();
   }
  }

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

  }
  #endregion

  public void RefurData()
  {
   string TypeID =Request.QueryString["TypeID"];//第一次请求结果为null
    if(TypeID + "Flag" != "Flag")//如果加Flag不等于Flag,表示ddlType改变过,触发过onchange事件
    {
      DDlInfoBind(TypeID);
    }

    if(!this.IsPostBack)
    {
      DDlTypeBind();
    }
  }

  //返回ddlInfo下拉框需要的值给xmlhttp
  private void DDlInfoBind(string TID)
  {
    string Mystr = "";
           int TypeID=int.Parse(TID);
           SqlDataReader dr=CDG.GetTypeInfo(TypeID);//此处用了数据访问层的代码,如要运行,必须自己写方法
    DataTable MyTab =Tools.ConvertDataReaderToDataTable(dr);

    if(MyTab.Rows.Count != 0)//判断是否有记录
    {
      for(int i=0;i<MyTab.Rows.Count;i++)//循环DataTable里的记录
      {
        Mystr += "," + MyTab.Rows[i][1].ToString() + "|" + MyTab.Rows[i][0].ToString();
     //DataTable每一行都有编号和记录,使用,和|分隔,在XMLPOST中用到
      }
      Mystr = Mystr.Substring(1);
    }
    Response.Write(Mystr);//向HTTP输出内容流写入一个字符数组
    Response.End();//停止该页的执行
  }

  /// <summary>
  /// 绑定第一个下拉框
  /// </summary>
  private void DDlTypeBind()
  {
    ddlType.DataSource=CDG.GetMType();//此处用了数据访问层的代码,如要运行,必须自己写方法
          ddlType.DataTextField="TypeName";
          ddlType.DataValueField="ID";
          ddlType.DataBind();
          ddlType.Items.Insert(0,"请选择");
          ddlType.Items[0].Selected=true;
    ddlType.Attributes.Add("onchange","XmlPost(this);");
  }

  private void btnSubmit_Click(object sender, System.EventArgs e)
  {
   try
   {
    int ID=int.Parse(Request.Form["ddlInfo"].ToString());//只是在服务器端得到ddlInfo选中的对应的编号
    Response.Write("<script>alert('"+ID+"')</script>");
    DDlTypeBind();
   }
   catch
   {}
  }

 }
}

posted @ 2009-04-11 12:44  智者生存  阅读(813)  评论(0编辑  收藏  举报