asp.net(c#)用Ajax调用web 服务实现省市县三级联动

本文介绍了一种使用jQuery和ASP.NET实现省市县三级联动选择框的方法。通过分层架构(包括Model、BLL和DAL层),结合自定义JS脚本和Web服务,实现了下拉列表的动态加载。

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

一,在aspx页面中引用三个dropdownlist或者三个下拉列表

这里主要标示是列表的ID,只要保证列表ID一致即可
<!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 id="Head1" runat="server">
    <title>jQuery + ASP.NET实现三级联动</title>
    <script src="js/jquery-1.4.1.min.js" type="text/javascript"></script><%--基于JQuery1.4.1的Ajax框架,主要好处是与后续版本的asp.net完全集成。--%>
    <script src="js/jin.chinaCity.js" type="text/javascript"></script>
    <style type="text/css">
        #drdProvince,#drdCity,#drdArea
        {
            margin-left:10px;
            width:120px;
        }
    </style>
</head>
<body>
    <form runat="server">
    <div>
        省:<asp:DropDownList ID="drdProvince" runat="server">
        </asp:DropDownList>
        市:<asp:DropDownList ID="drdCity" runat="server">
        </asp:DropDownList>
        县:<asp:DropDownList ID="drdArea" runat="server">
        </asp:DropDownList>
    </div>
    </form>
</body>
</html>

二,OK,现在是基础建设,此处是通过三层架构来实现,代码如下

数据表如下

ok,现在依次插入Model,Bll,DAL的代码
namespace Model
{
    public class ChinaCity
    {
        private int _cityId;
        private string _cityName;
        private string _cityPinYin;
        private string _cityPostCode;
        private string _citySimple;
        private string _generateTime;

        public int CityId
        {
            get { return _cityId; }
            set { _cityId = value; }
        }
        public string CityName
        {
            get { return _cityName; }
            set { _cityName = value; }
        }
        public string CityPinYin
        {
            get { return _cityPinYin; }
            set { _cityPinYin = value; }
        }
        public string CityPostCode
        {
            get { return _cityPostCode; }
            set { _cityPostCode = value; }
        }
        public string CitySimple
        {
            get { return _citySimple; }
            set { _citySimple = value; }
        }
        public string GenerateTime
        {
            get { return _generateTime; }
            set { _generateTime = value; }
        }
    }
}
BLL
namespace Bll
{
    public class ChinaCity
    {
        Dal.ChinaCity cityDAL = new Dal.ChinaCity();
        //返回City的泛型列表
        public List<Model.ChinaCity> CityList(string code)
        {
            List<Model.ChinaCity> list = new List<Model.ChinaCity>();
            DataTable dt = cityDAL.CityList(code);
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    Model.ChinaCity cityModel = new Model.ChinaCity();
                    cityModel.CityId = int.Parse(dt.Rows[i]["CityId"].ToString());
                    cityModel.CityName = dt.Rows[i]["CityName"].ToString();
                    cityModel.CityPostCode = dt.Rows[i]["CityPostCode"].ToString();
                    list.Add(cityModel);
                }
            }
            return list;
        }
    }
}
DAL
namespace Dal
{
    public class ChinaCity
    {
        public DataTable CityList(string pcode)//CityPostCode
        {
            string SQL = "SELECT * FROM ChinaCity WHERE 1=1";
            if (!string.IsNullOrEmpty(pcode))
            {
                if (pcode.Substring(2, 2) != "00")//县
                {
                    //<>不等于, >= 大于等于,<=小于等于
                    SQL = SQL + " AND RIGHT(CityPostCode,2)<>'00' AND LEFT(CityPostCode,4)=LEFT("+pcode+",4)";
                }
                else//市,AND (RIGHT(CityPostCode, 4) <> '0000')
                {
                    SQL = SQL + " AND RIGHT(CityPostCode,2)='00' AND LEFT(RIGHT(CityPostCode,4),2)<>'00' AND LEFT(CityPostCode,2)=LEFT(" + pcode + ",2)";
                }
            }
            else
            {
                SQL = SQL + " AND LEFT(CityPostCode,2)<>'00' AND RIGHT(CityPostCode,4)='0000'";
            }
            SQL = SQL + "  order by CityPostCode";
            DataTable dt=new DataTable();
            Commom.DBHelper.Query(SQL, dt);
            return dt;
        }

    }
}

三,建一个自有的js文件,里面放入代码如下

/* .................Ajax实现省市县三级联动.............*/
jQuery(document).ready(function () {
    var drd1 = jQuery("#drdProvince");
    var drd2 = jQuery("#drdCity");
    var drd3 = jQuery("#drdArea");
   
    loadCityAddress("", drd1); //填充省的数据
    //给省绑定事件,触发事件后填充市的数据,并同时清空县的数据
    //$(selector).bind(event,data,function),规定向被选元素添加的一个或多个事件处理程序,以及当事件发生时运行的函数。
    jQuery(drd1).bind("change keyup", function () {
        var provinceID = drd1.attr("value");
        loadCityAddress(provinceID, drd2);
        $(drd3)[0].length = 0;
        //drd2.fadeIn("slow");当加载页面时隐藏了控件,通过加载淡入数据
    });
    //给市绑定事件,触发事件后填充县的数据
    jQuery(drd2).bind("change keyup", function () {
        var cityID = drd2.attr("value");
        loadCityAddress(cityID, drd3);
    });
});
//关键函数,调用web服务:ChinaCity.asmx/GetCityList 方法,得到一组关于城市地址的json数据。
//通过DOM对象清除下拉列表,然后jQuery(item).append方法插入html
function loadCityAddress(val, item) {
    jQuery.ajax({
        type: "post",
        url: "ChinaCity.asmx/GetCityList",
        data: {
            code: val,
            a: Math.random()
        },
        error: function () {
            return false;
        },
        success: function (data) {
            var i;
            var json = eval(data);
            item[0].length = 0;
            //for (var i = item[0].length; i > 0; i--) {
            //    obj.remove(item[0].options[i]);
            //}
            //$(item).append("<option value='' selected='selected'>请选择</option>");
            for (i = 0; i < json.length; i++) {
                item.append(jQuery("<option></option>").val(json[i]._cityPostCode).html(json[i]._cityName));
            };
        }
    });
}

四,那么,最后一步,建web 服务,主要是方便Ajax调用,里面代码如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Text;

/// <summary>
///ChinaCity 的摘要说明
/// </summary>
//[WebService(Namespace = "http://tempuri.org/")]
[WebService(Namespace = "http://microsoft.com/webservices/")]

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

//[System.ComponentModel.ToolboxItem(false)]

//若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。 
// [System.Web.Script.Services.ScriptService]
public class ChinaCity : System.Web.Services.WebService {

    public ChinaCity () {

        //如果使用设计的组件,请取消注释以下行 
        //InitializeComponent(); 
    }

    [WebMethod]
    public string HelloWorld()
    {
        return "Hello World";
    }
    
    Bll.ChinaCity cityBLL = new Bll.ChinaCity();
    Model.ChinaCity cityModel = new Model.ChinaCity();

    [WebMethod]
    public void GetCityList(string code)
    {

        StringBuilder strBuilder = new StringBuilder();

        List<Model.ChinaCity> cm = cityBLL.CityList(code);
        strBuilder.Append("[");
        if (cm.Count > 0)
        {
            for (int i = 0; i < cm.Count; i++)
            {
                cityModel = cm[i];
                strBuilder.Append("{");
                strBuilder.AppendFormat(@"""_cityName"":""{0}"",", cityModel.CityName);
                strBuilder.AppendFormat(@"""_cityPostCode"":""{0}""", cityModel.CityPostCode);
                strBuilder.Append("}");
                if (i < cm.Count - 1)
                {
                    strBuilder.Append(",");
                }
            }
        }
        strBuilder.Append("]");
        System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
        System.Web.HttpContext.Current.Response.Write(strBuilder.ToString());
    }
}
完成,现在运行即可自动加载省市县的三级自动加载;
有另一个实现三级联动的方法是数据表的数据用XML格式来保存,适合用于轻量级的应用,步骤其实差不多。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值