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

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;
            }
        }


 


以上为关键源代码。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这个是ajax 实现DropDownList无刷联动。里面有数据库结构和内容,表结构的是sql2000的, 关键代码: <SCRIPT language="javascript"> //城市------------------------------ function cityResult() { var city=document.getElementById("DropDownList1"); AjaxMethod.GetCityList(city.value,get_city_Result_CallBack); } function get_city_Result_CallBack(response) { if (response.value != null) { //debugger; document.all("DropDownList2").length=0;          var ds = response.value; if(ds != null && typeof(ds) == "object" && ds.Tables != null) { for(var i=0; i<ds.Tables[0].Rows.length; i++)      {      var name=ds.Tables[0].Rows[i].CityName;        var id=ds.Tables[0].Rows[i].ProvinceID;        document.all("DropDownList2").options.add(new Option(name,id));      } } } else { document.all("DropDownList2").length=0; } return } //市区---------------------------------------- function areaResult() { var area=document.getElementById("DropDownList2"); AjaxMethod.GetAreaList(area.value,get_area_Result_CallBack); } function get_area_Result_CallBack(response) { if (response.value != null) { document.all("DropDownList3").length=0;          var ds = response.value; if(ds != null && typeof(ds) == "object" && ds.Tables != null) { for(var i=0; i<ds.Tables[0].Rows.length; i++)      {        var name=ds.Tables[0].Rows[i].ProvinceName;        var id=ds.Tables[0].Rows[i].id;        document.all("DropDownList3").options.add(new Option(name,id));      } } } else { document.all("DropDownList3").length=0; } return } </SCRIPT>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值