jQuery+Asp.Net实现省市二级联动功能

作者:袖梨 2022-06-25

本文实例讲述了jQuery+Asp.Net实现省市二级联动功能的方法。分享给大家供大家参考,具体如下:

页面html:

 

 代码如下复制代码

<%@ Page Language="C#"AutoEventWireup="true"CodeFile="ddlAjax.aspx.cs"Inherits="ThreeAjaxDrop_ddlAjax"%>

DropDownList三级联动

三级联动: & amp;nbsp;

 

asp.net部分:

(1)Default.aspx.cs

 

 代码如下复制代码

publicpartialclassThreeAjaxDrop_Default : System.Web.UI.Page

{

  protectedvoidPage_Load(objectsender, EventArgs e)

  {

    stringsql ="select * from province";

    stringstrTemp =""text":"{0}","value":"{1}"";//构造格式字符串 {"text":"北京","value":"00001"}

    StringBuilder sb =newStringBuilder();

    OleDbDataReader reader = OleDBHelper.ExecuteReader(sql);

    while(reader.Read())

    {

      stringstr1 =string.Format(strTemp, reader["province"].ToString(), reader["provinceID"].ToString());

      sb.Append("{"+str1+"},");

    }

    reader.Close();

    stringjson = sb.ToString();

    Response.Write("["+json.Substring(0,json.Length-1)+"]");

  }

}

 

(2)HandlerDropDownAjax.ashx

 

 代码如下复制代码

publicclassHandlerDropDownAjax : IHttpHandler {

  publicvoidProcessRequest (HttpContext context) {

    if(context.Request.QueryString["type"] !=null&& context.Request.QueryString["fid"] !=null)

    {

      stringtype = context.Request.QueryString["type"].ToString();//主要用于识别是查询city还是area表

      stringfid = context.Request.QueryString["fid"].ToString();  //城市或区域的父ID

      stringsql ="select * from "+ type +" where father='"+ fid +"'";

      //构造数据的类型[{"text":"南昌","value":"0001"},{"text":"上饶","value":"0002"}]

      //string strTemp = "{"text":"{0}","value":"{1}"}";//这里犯了个错误:直接这样构造会出错,因为大括号里又有格式大括号,解析会出错

      stringstrTemp =""text":"{0}","value":"{1}"";//构造格式字符串 {"text":"北京","value":"00001"}

      StringBuilder sb =newStringBuilder();

      OleDbDataReader reader = OleDBHelper.ExecuteReader(sql);

      while(reader.Read())

      {

        stringstr1 =string.Format(strTemp, reader[2].ToString(), reader[1].ToString());

        sb.Append("{"+ str1 +"},");//两边的大括号格式化后加上

      }

      reader.Close();

      stringjson = sb.ToString();

      context.Response.Write("["+ json.Substring(0, json.Length - 1) +"]");//Substring的作用是去掉最后一个'逗号'

    }

  }

  publicboolIsReusable {

    get{

      returnfalse;

    }

  }

}

 

希望本文所述对大家asp.net程序设计有所帮助。

相关文章

精彩推荐