学习笔记 vs2008+sql2005+jquery1.4+json+ajax省市区三级连动

来源:互联网 发布:淘宝新店能上什么活动 编辑:程序博客网 时间:2024/05/07 13:03

//一、第一步在网站目录下建一个GetArea.ashx一般处理文件

using System;

using System.Collections;

using System.Web;

using System.Web.Services;

using System.Text;

using System.Data;

using System.Data.SqlClient;

 

using System.Collections.Generic;

 

 

namespace Web

{

    /// <summary>

    /// 获取地区

    /// </summary>

    [WebService(Namespace = "http://tempuri.org/")]

    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

    public class GetArea : IHttpHandler

    {

      

 

        public void ProcessRequest(HttpContext context)

        {

           

 

            if (context.Request.Params.Count > 0 && context.Request["id"] != null && context.Request["type"] != null && context.Request["type"] == "area")

            {

                string id = string.Empty;

                string type = string.Empty;

                AreaBll bll = new AreaBll();

                if (context.Request["id"] != null)

                {

                    id = context.Request["id"];//获取父类型编号()

                }

 

                StringBuilder sb = new StringBuilder();

                sb.AppendFormat("[");

                string sql = string.Format("select [AreaId],[AreaName] from T_Area where ParentId=@ParentId ");

                SqlParameter[] parms = { new SqlParameter("@ParentId", SqlDbType.Int) };

                parms[0].Value = id;

                DataTable= SqlHelper.GetDataTable(CommandType.Text, sql, parms);

                StringBuilder sb = new StringBuilder();

                sb.AppendFormat("[");

                for (int i = 0; i < list.Rows.Count; i++)

                {

                    sb.AppendFormat("{{/"id/":/"{0}/",/"name/":/"{1}/"}}", dt.Rows[i].ItemArray[0].ToString(), dt.Rows[i].ItemArray[1].ToString());

                    if (i != dt.Rows.Count - 1)

                        sb.AppendFormat(",");

                }

                sb.AppendFormat("]");

                context.Response.Write(sb.ToString());

                context.Response.End();

            }

        }

 

        public bool IsReusable

        {

            get

            {

                return false;

            }

        }

    }

}

 

//一、第二步新建OperArea.js文件

 

$(document).ready(function() {

   

    //绑定城市

    $('#MyProvince').change(function() {

        $('#MyArea').attr('disabled', 'disabled');

        AjaxFn('MyProvince', 'MyCity');

    });

    //绑定地区

    $('#MyCity').change(function() {

        AjaxFn('MyCity', 'MyArea');

    });

    function AjaxFn(FID, id) {

         $.ajax({

            type: 'post',

            dataType: 'json',

            url: '../GetArea.ashx', //注意请求地址路径

            data: 'id=' + escape($('#' + FID).val()) + '&&type=area',

            beforeSend: function(XMLHttpRequest) { $('#' + id).html('正在加载...');},

            success: function(data, textStatus) {

                Format(data, id); //格式化字符串

            },

            complete: function(XMLHttpRequest, textStatus) {

            },

            error: function(XMLHttpRequest, textStatus,errorThrown) {alert(textStatus.toString());

               alert('出错了');

            }

        });

    }

});

//格式化字符串

function Format(data, id) {

 

 

    $.each(data,function(i){ 

 

        $('#' + id).append('<option value="' + data[i].id+ '">' + data[i].name+ '</option>');

     } );                                               

    $('#' + id).removeAttr('disabled');

}

 

//一、第三步

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UserAddress.aspx.cs" Inherits="Web.Default " %>

 

<!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>省市县vs2008+sql2005+jquery+json+ajax</title>

    <script src="../js/jquery-1.4.1.min.js" type="text/javascript"></script>

    <script src="../js/OperArea.js" type="text/javascript"></script>

</head>

 

 

<body>

<form id="from1" runat="server">

 

              <div id="GetArea">

                    <select id="MyProvince" runat="server"></select>

                    <select id="MyCity" disabled="disabled"  runat="server">

                        <option value="0">请选择城市</option></select>

                    <select id="MyArea" disabled="disabled"  runat="server">

                        <option value="0">请选择地区</option></select>

              </div>

</form>

</body>

</html>

 

 

        protected void Page_Load(object sender, EventArgs e)

        {

            if (!Page.IsPostBack)

            {

                BindProvinces();

            }

        }

 

 

 

        //获取省份

        private void BindProvinces()

        {

            string sql = "select [AreaId],[AreaName] from T_Area where ParentId=0";//得到所有的省份

            DataTable dt = SqlHelper.GetDataTable(CommandType.Text, sql, null);

 

            if (dt != null && dt.Rows.Count > 0)

            {

                this.MyProvince.DataSource = dt;

                this.MyProvince.DataTextField = "AreaName";

                this.MyProvince.DataValueField = "AreaId";

                this.MyProvince.DataBind();

                this.MyProvince.Items.Insert(0, new ListItem("请选择省", "0"));

            }

        }

 

原创粉丝点击