利用Ajax来实现下拉框的三级联动

本文介绍了一种实现省市县三级联动下拉框的方法,包括配置web.config文件、创建AjaxFunctions类以及编写AreaSelect.aspx页面的前后端代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

常看一些网站,有省份、市、县三个下拉框,且有联动的功能。某天闲来无聊,试做了一个,微笑


数据库表




1.在web.config的<system.web>下加入代码如下

<httpHandlers>
      <add verb="POST,GET" path="ajax/*.ashx" type="Ajax.PageHandlerFactory, Ajax" />
</httpHandlers>

2.新建一个类库ajaxApp(添加引用Ajax.dll),并添加一个类AjaxFunctions       

using System;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;


namespace ajaxApp
{
    public class AjaxFunctions
    {
        public static string ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;


        public static DataTable GetDataSet(string sql)
        {
            SqlDataAdapter sda = new SqlDataAdapter(sql, ConnectionString);
            DataSet ds = new DataSet();
            sda.Fill(ds);
            return ds.Tables[0];
        }


        public DataTable GetProvince()
        {
            string sql = "select provinceId,provinceNm from province";
            DataTable dt = GetDataSet(sql);
            return dt;
        }


        [Ajax.AjaxMethod()]
        public DataSet GetCity(string id)
        {
            DataSet ds = new DataSet();


            string sqlCity = "select cityId,cityNm from city where cityFather = '" + id + "' order by cityId";
            DataTable dtCity = GetDataSet(sqlCity);
            dtCity.TableName = "dtCity";
            ds.Tables.Add(dtCity.Copy());


            string strFirstCity = "";
            if (dtCity != null && dtCity.Rows.Count >0)
            {
                strFirstCity = dtCity.Rows[0]["cityId"].ToString();
            }


            string sqlArea = "select areaId,areaNm from area where areaFather = '" + strFirstCity + "' order by areaId";
            DataTable dtArea = GetDataSet(sqlArea);
            dtArea.TableName = "dtArea";
            ds.Tables.Add(dtArea.Copy());


            return ds;
        }


        [Ajax.AjaxMethod()]
        public DataTable GetArea(string id)
        {
            string sql = "select areaId,areaNm from area where areaFather = '" + id + "' order by areaId";
            DataTable dt = GetDataSet(sql);
            return dt;
        }


    }
}


3.新建一个web窗体 AreaSelect

AreaSelect.aspx代码

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AreaSelect.aspx.cs" Inherits="WebApplication1.MyTest.AreaSelect" %>


<!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>
    <title></title>
</head>
<body>
    <form id="Form1" method="post" runat="server">
    <table>
        <tr>
            <td>
                <asp:DropDownList ID="ddlProvince" runat="server" Width="100px">
                </asp:DropDownList>
            </td>
            <td>
                <asp:DropDownList ID="ddlCity" runat="server" Width="100px">
                </asp:DropDownList>
            </td>
            <td>
                <asp:DropDownList ID="ddlArea" runat="server" Width="100px">
                </asp:DropDownList>
            </td>
        </tr>
    </table>
    <script language="javascript" type="text/javascript">


        function ddl_getcith(obj) {
            var list = document.getElementById("ddlProvince");
            var index = list.selectedIndex;
            var pValue = list.options[index].value;
            AjaxFunctions.GetCity(pValue, GetCity_CallBack);
        }
        //城市回调函数
        function GetCity_CallBack(response) {
            var ds = response.value;
            if (ds != null) {
                var list = document.getElementById("ddlCity");
                list.options.length = 0;
                for (var i = 0; i < ds.Tables[0].Rows.length; i++) {
                    list.options.add(new Option(ds.Tables[0].Rows[i]["cityNm"].toString(), ds.Tables[0].Rows[i]["cityId"].toString()));
                }


                var list2 = document.getElementById("ddlArea");
                list2.options.length = 0;
                for (var i = 0; i < ds.Tables[1].Rows.length; i++) {
                    list2.options.add(new Option(ds.Tables[1].Rows[i]["areaNm"].toString(), ds.Tables[1].Rows[i]["areaId"].toString()));
                }
            }
            else {
                alert("Error. [3001] " + response.request.responseText);
            }
        }
        function ddl_getarea(obj) {
            var list = document.getElementById("ddlCity");
            var index = list.selectedIndex;
            var pValue = list.options[index].value;
            AjaxFunctions.GetArea(pValue, GetArea_CallBack);
        }
        //县的回调函数
        function GetArea_CallBack(response) {
            var dt = response.value;
            if (dt != null) {
                var list = document.getElementById("ddlArea");
                list.options.length = 0;
                for (var i = 0; i < dt.Rows.length; i++) {
                    list.options.add(new Option(dt.Rows[i]["areaNm"].toString(), dt.Rows[i]["areaId"].toString()))
                }
            }
            else {
                alert("Error. [3001] " + response.request.responseText);
            }
        }			
				
    </script>
    </form>
</body>
</html>

AreaSelect.aspx.cs代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ajaxApp;
using System.Data;


namespace WebApplication1.MyTest
{
    public partial class AreaSelect : System.Web.UI.Page
    {
        AjaxFunctions af = new AjaxFunctions();


        private void Page_Load(object sender, System.EventArgs e)
        {
            if (!IsPostBack)
            {
                Ajax.Utility.RegisterTypeForAjax(typeof(AjaxFunctions));


                this.ddlProvince.Attributes.Add("onchange", "ddl_getcith(this)");
                this.ddlCity.Attributes.Add("onchange", "ddl_getarea(this)");


                DataTable dt = af.GetProvince();
                this.ddlProvince.DataSource = dt;
                this.ddlProvince.DataValueField = "provinceId";
                this.ddlProvince.DataTextField = "provinceNm";
                this.ddlProvince.DataBind();
                this.ddlProvince.Items.Insert(0, new ListItem(""));
            }
        }


    }
}

运行了一下,效果还可以。但是有几个注意点得留意下,具体如下:

1.在web.config的<system.web>下一定要记得加

<httpHandlers>
      <add verb="POST,GET" path="ajax/*.ashx"  type="Ajax.PageHandlerFactory, Ajax" />
</httpHandlers>

2.AjaxFunctions类中有两个方法都要在asp前台页面用js调用,记得方法前要加 [Ajax.AjaxMethod()]

3.AreaSelect.aspx.cs代码的page_load中要加入 Ajax.Utility.RegisterTypeForAjax(typeof(AjaxFunctions));

4.在前台js中调用后台时,一定要在方法名前加类名 AjaxFunctions.GetCity(pValue, GetCity_CallBack);


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值