ASP.NET中DropDownList无刷新联动实现方法

来源:互联网 发布:轿车送货软件 编辑:程序博客网 时间:2024/04/29 12:53

DropDownList联动在实际的编程工作中被广泛使用,如果使用微软提供的事件操作方法,会导致页面的刷新,用户体验不好,所以DropDownList的无刷新联动是很多人关心的话题。本文参考了网上的部分资料,以部门和人员的二级联动为例,介绍了DropDownList的二级联动无刷新实现方式。

一、数据库的建立

1、部门表Department

2、人员表Employee

 

二、新建aspx页面,aspx页面代码如下:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Department.aspx.cs" Inherits="ajaxDemo.Department" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server">    <title></title>     <script type="text/javascript" src="ajax_func.js"></script>    <script type="text/javascript" language="javascript">               function populateClass() {            var f = document.getElementById("dropEmployee");            if (http_request.readyState == 4) {                if (http_request.status == 200) {                    var list = http_request.responseText;                    var classList = list.split("|");                    f.options.length = 1;                    for (var i = 0; i < classList.length; i++) {                        var tmp = classList[i].split(",");                        f.add(new Option(tmp[1], tmp[0]));                    }                } else {                    alert("您所请求的页面有异常。");                }            }        }        function changDepartment(va) {            if (va != '0') {                var url = "Handler1.ashx?id=" + va;                send_request("GET", url, null, "text", populateClass);            }        }        </script></head><body>    <form id="form1" runat="server">    <br />    <br />    <br />     <asp:DropDownList ID="dropDepartment" runat="server">                 <asp:ListItem Value="0">--请选择--</asp:ListItem>     </asp:DropDownList>     <asp:DropDownList ID="dropEmployee" runat="server">             <asp:ListItem Value="0">--请选择--</asp:ListItem>     </asp:DropDownList>    <div>        </div>    </form></body></html>

 

三、aspx.cs页面代码如下:

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Data;namespace ajaxDemo{    public partial class Department : System.Web.UI.Page    {        protected void Page_Load(object sender, EventArgs e)        {            DataSet ds = SqlDataAccess.GetDepartment();            string id, department;            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)            {                id = ds.Tables[0].Rows[i]["id"].ToString();                department = ds.Tables[0].Rows[i]["department"].ToString();                this.dropDepartment.Items.Add(new ListItem(department, id));            }            dropDepartment.Attributes.Add("onchange", "changDepartment(this.value)");        }    }}


四、Handler1.ashx页面代码如下:

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Data;namespace ajaxDemo{    /// <summary>    /// Handler1 的摘要说明    /// </summary>    public class Handler1 : IHttpHandler    {        public void ProcessRequest(HttpContext context)        {            context.Response.ContentType = "text/plain";            string id = context.Request.QueryString["id"];            context.Response.Write(getEmployee(id));        }        public string getEmployee(string id)        {            DataSet ds = SqlDataAccess.GetEmployee(id);            string str = "";            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)            {                if (i == ds.Tables[0].Rows.Count - 1)                {                    str += ds.Tables[0].Rows[i]["id"].ToString() + "," + ds.Tables[0].Rows[i]["name"].ToString();                }                else                {                    str += ds.Tables[0].Rows[i]["id"].ToString() + "," + ds.Tables[0].Rows[i]["name"].ToString() + "|";                }            }            return str.Trim();        }        public bool IsReusable        {            get            {                return false;            }        }    }}

 

五、ajax_func.js代码如下:

var http_request = false;function send_request(method, url, content, responseType, callback) {    http_request = false;    if (window.XMLHttpRequest) {//Mozilla浏览器        http_request = new XMLHttpRequest();        if (http_request.overrideMimeType) {            http_request.overrideMimeType("text/xml");        }    }    else {        try {            http_request = new ActiveXObject("Msxml2.XMLHTTP");        } catch (e) {            try {                http_request = new ActiveXObject("Microsoft.XMLHTTP");            } catch (e) { }        }    }    if (!http_request) {        window.alert("不能创建XMLHttpRequest对象实例。");        return false;    }    if (responseType.toLowerCase() == "text") {        http_request.onreadystatechange = callback;    } else {        window.alert("响应类别参数错误。");        return false;    }    if (method.toLowerCase() == "get") {        http_request.open(method, url, true);    }    else if (method.toLowerCase() == "post") {        http_request.open(method, url, true);        http_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");    } else {        window.alert("http请求类别参数错误。");        return false;    }    http_request.send(content);}

 

六、SqlDataAccess.cs中获取部门及人员代码

        /// <summary>        /// 获得部门信息         /// </summary>        /// <returns></returns>        public static DataSet GetDepartment()        {            string sql = "select * from Department";            SqlCommand cmd = new SqlCommand();            using (SqlConnection conn = new SqlConnection(SqlHelper.ConnectionString))            {                DataSet ds = SqlHelper.ExecuteDataSet(CommandType.Text, sql);                return ds;            }        }        /// <summary>        /// 获得人员信息        /// </summary>        /// <returns></returns>        public static DataSet GetEmployee(string departmentId)        {            string sql = "select * from Employee where departmentId=" + departmentId + "";            SqlCommand cmd = new SqlCommand();            using (SqlConnection conn = new SqlConnection(SqlHelper.ConnectionString))            {                DataSet ds = SqlHelper.ExecuteDataSet(CommandType.Text, sql);                return ds;            }        }


 


以上为关键源代码。

0 0
原创粉丝点击