[转] ASP.NET使用AJAX联动

数据库
CREATE TABLE [dbo].[LinkAge01] (
[id] [int] IDENTITY (1, 1) NOT NULL ,
[name] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]
GO

CREATE TABLE [dbo].[LinkAge02] (
[id] [int] IDENTITY (1, 1) NOT NULL ,
[lID] [int] NOT NULL ,
[name] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL
) ON [PRIMARY]
GO

页面index.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="index.aspx.cs" Inherits="_index" %>
<html>
<head runat="server">
    <title>LinkAgeTest.</title>
    <script language="javascript">
    //jb函数会根据不同的浏览器初始化个xmlhttp对象
    function jb()
    {
        var A=null;
        try
        {
            A=new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch(e)
        {
            try
            {
                A=new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch(oc)
            {
                A=null
            }
        }
        if ( !A && typeof XMLHttpRequest != "undefined" )
        {
            A=new XMLHttpRequest()
        }
        return A
    }

    //下面Go函数是父列表框改变的时候调用,参数是选择的条目
    function Go()
    {
        var svalue = document.getElementById("ddl01").value;//得到选择框的下拉列表的value
        var weburl = "index.aspx?id="+svalue;//定义要处理数据的页面  
        var xmlhttp = jb();//初始化个xmlhttp对象
        xmlhttp.open("get",weburl,true); //提交数据,第一个参数最好为get,第三个参数最好为true
        //alert(xmlhttp.responseText);
        //如果已经成功的返回了数据
        xmlhttp.onreadystatechange=function()
        {
            if(xmlhttp.readyState==4)//4代表成功返回数据
            {
                var result = xmlhttp.responseText;//得到服务器返回的数据   
                document.getElementById("ddl02").length = 0;//先清空ddlC的所有下拉项  
                document.getElementById("ddl02").options.add(new Option("请选择","0")); //给ddlC加个全部型号的,注意是Option不是option
                if(result!="")//如果返回的数据不是空
                {   
                    var allArray = result.split(",");//把收到的字符串按照,分割成数组
                    //循环这个数组,注意是从1开始,因为收到的字符串第一个字符是,号,所以分割后第一个数组为空
                    for(var i=1;i<allArray.length;i++)
                    {
                        var thisArray = allArray[i].split("|");//在把这个字符串按照|分割成数组
                        //为ddlC添加条目
                        document.getElementById("ddl02").options.add(new Option(thisArray[0].toString(),thisArray[1].toString()));
                    }
                }
            }
        }
        //发送数据,请注意顺序和参数,参数一定为null或者""
        xmlhttp.send(null);
    }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
       
        省:<select id="ddl01" name="ddl01" runat="server" onchange="Go(this)"></select> 
        市:<select id="ddl02" name="ddl02" runat="server" ></select> 
        <%--
        省:<asp:dropdownlist ID="ddl01" runat="server" onchange="Go(this)"></asp:dropdownlist> 
        市:<asp:dropdownlist ID="ddl02" runat="server"></asp:dropdownlist>
        --%>
        <asp:Button ID="btnOk" runat="server" Text=" 确 定 " OnClick="btnOk_Click" />
       
    </div>
    </form>
</body>
</html>

类文件 index.cs
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class _index : System.Web.UI.Page
{
    private SqlConnection con;
    private SqlDataAdapter sda;
    private SqlCommand cmd;
    private DataSet ds;
    private SqlDataReader sdr;
   
    //数据库开连接字符串
    public static String conStr = "server=.; database=Test; uid=sa; pwd=sa";

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!IsPostBack)
            {
                con = new SqlConnection(conStr);
                sda = new SqlDataAdapter("select * from LinkAge01", con);
                ds = new DataSet();
                sda.Fill(ds, "LinkAge01");
                ds.Tables["LinkAge01"].DefaultView.Sort = "id asc";
                ddl01.DataSource = ds.Tables["LinkAge01"].DefaultView;
                ddl01.DataValueField = "id";
                ddl01.DataTextField = "name";
                ddl01.DataBind();
            }
            Response.Write("Request.Form[ddl02]:" + Request.Form["ddl02"] + "<br />");
            BindDrop();
        }
        catch (Exception ex)
        {
            Response.Write("error:" + ex.ToString());
        }       
    }

    protected void btnOk_Click(object sender, EventArgs e)
    {
        try
        {
            Response.Write(ddl01.Items[ddl01.SelectedIndex].Text + "<br/>");
            Response.Write(ddl02.Items[ddl02.SelectedIndex].Text + "<br/>");
        }
        catch (Exception ex)
        {
            Response.Write("error:" + ex.ToString());
        }
    }

    protected void BindDrop()
    {
        String str = Request.QueryString["id"];
        String str1 = ddl01.Items[ddl01.SelectedIndex].Value;
        Response.Write("str1=" + str1 + "<br/>");
        String a = str + "abc";
        if (str + "abc" != "abc")//如果str加个字符串!=原来的字符串则说明触发过ddlS的onchange事件
            BindChild(str);//触发过ddlS的onchange事件
        else
            BindParent(str1);//第一次加载活刷新
    }

    protected void BindParent(String str1)
    {
        try
        {
            //如果是第一次请求或者是刷新这个页面则根据ddlS的值来选择
            //把参数转化成int
            int i = Convert.ToInt32(str1);
            ddl02.Items.Clear();
            ddl02.Items.Add(new ListItem("请选择", "0"));
            con = new SqlConnection(conStr);
            cmd = new SqlCommand("select * from LinkAge02 where lID=" + i, con);
            con.Open();
            sdr = cmd.ExecuteReader();
            while (sdr.Read())
            {
                ddl02.Items.Add(new ListItem(sdr["name"].ToString(), sdr["id"].ToString()));
            }
            sdr.Close();
            con.Close();
            ddl02.Items[0].Selected=true;
            ddl01.Items[0].Selected = false;
            //添加下面这话的意思是当点提交按钮提交窗体的时候第二个ddl02的状态能够得到保存
            Response.Write("Request.Form[ddl02]:"+Request.Form["ddl02"]+"<br />");
            ddl02.Value = Request.Form["ddl02"];

        }
        catch (Exception ex)
        {
            Response.Write("error:" + ex.ToString());
        }
    }

    protected void BindChild(String str)
    {
        //通过js给包括dropdownlist任何控件添加的内容不会被保存状态
        //把参数转化成int
        int i = Convert.ToInt32(str);
        String result = "";
        Response.Clear();
        con = new SqlConnection(conStr);
        cmd = new SqlCommand("select * from LinkAge02 where lID=" + i, con);
        con.Open();
        sdr = cmd.ExecuteReader();
        while (sdr.Read())
        {
            result += "," + sdr["name"].ToString() + "|" + sdr["id"].ToString();
        }
        sdr.Close();
        con.Close();
        Response.Write(result);
        Response.Flush();
        Response.Close();
       
    }
}

原文地址:http://blog.csdn.net/mathew3625/archive/2008/04/13/2288707.aspx

posted @ 2009-05-08 16:01  funnyzak  阅读(143)  评论(0编辑  收藏  举报