富贵资源网 Design By www.hznty.com

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

页面html:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ddlAjax.aspx.cs" Inherits="ThreeAjaxDrop_ddlAjax" %>
<!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>DropDownList三级联动</title>
<style type="text/css">
*{margin:0; padding:0;}
body{font-size:12px; font-family:Arial @宋体;}
</style>
<script type="text/javascript" src="/UploadFiles/2021-04-02/jquery-1.4.min.js">

asp.net部分:

(1)Default.aspx.cs

public partial class ThreeAjaxDrop_Default : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
    string sql = "select * from province";
    string strTemp = "\"text\":\"{0}\",\"value\":\"{1}\""; //构造格式字符串 {"text":"北京","value":"00001"}
    StringBuilder sb = new StringBuilder();
    OleDbDataReader reader = OleDBHelper.ExecuteReader(sql);
    while (reader.Read())
    {
      string str1 = string.Format(strTemp, reader["province"].ToString(), reader["provinceID"].ToString());
      sb.Append("{"+str1+"},");
    }
    reader.Close();
    string json = sb.ToString();
    Response.Write("["+json.Substring(0,json.Length-1)+"]");
  }
}

(2)HandlerDropDownAjax.ashx

public class HandlerDropDownAjax : IHttpHandler {
  public void ProcessRequest (HttpContext context) {
    if (context.Request.QueryString["type"] != null && context.Request.QueryString["fid"] != null)
    {
      string type = context.Request.QueryString["type"].ToString(); //主要用于识别是查询city还是area表
      string fid = context.Request.QueryString["fid"].ToString();   //城市或区域的父ID
      string sql = "select * from " + type + " where father='" + fid + "'";
      //构造数据的类型[{"text":"南昌","value":"0001"},{"text":"上饶","value":"0002"}]
      //string strTemp = "{\"text\":\"{0}\",\"value\":\"{1}\"}";//这里犯了个错误:直接这样构造会出错,因为大括号里又有格式大括号,解析会出错
      string strTemp = "\"text\":\"{0}\",\"value\":\"{1}\""; //构造格式字符串 {"text":"北京","value":"00001"}
      StringBuilder sb = new StringBuilder();
      OleDbDataReader reader = OleDBHelper.ExecuteReader(sql);
      while (reader.Read())
      {
        string str1 = string.Format(strTemp, reader[2].ToString(), reader[1].ToString());
        sb.Append("{" + str1 + "},"); //两边的大括号格式化后加上
      }
      reader.Close();
      string json = sb.ToString();
      context.Response.Write("[" + json.Substring(0, json.Length - 1) + "]"); //Substring的作用是去掉最后一个'逗号'
    }
  }
  public bool IsReusable {
    get {
      return false;
    }
  }
}

更多关于asp.net相关内容感兴趣的读者可查看本站专题:《asp.net优化技巧总结》、《asp.net字符串操作技巧汇总》、《asp.net操作XML技巧总结》、《asp.net文件操作技巧汇总》、《asp.net ajax技巧总结专题》及《asp.net缓存操作技巧总结》。

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

富贵资源网 Design By www.hznty.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
富贵资源网 Design By www.hznty.com