search
HomeBackend DevelopmentC#.Net TutorialDetailed explanation of how Asp.Net+jQuery realizes the secondary linkage function of provinces and cities

This article mainly introduces the method of jQuery+Asp.Net to realize the secondary linkage function of provinces and cities, involving asp.net database reading and stringConversion related operation skills, friends in need can refer to the following

The example of this article describes the method of jQuery+Asp.Net to realize the secondary linkage function of provinces and cities. Share it with everyone for your reference, the details are as follows:

Page 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="../js/jquery-1.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
//加载完成后绑定省份数据
$.getJSON("Default.aspx", function(data) { //data的数据格式[{"text":"北京","value":"0001"},{"text":"江西","value":"0031"}]
//alert(data[0].text+"|"+data[0].value);
$.each(data, function(index, value) {
//alert(value.text + "|" + value.value);
$("#selProvince").append("<option value=&#39;" + value.value + "&#39;>" + value.text + "</option>");
});
});
//省份的值改变,则要绑定出城市下拉框
$("#selProvince").change(function(){
document.getElementById("selArea").options.length=1; //先清掉县下拉框的的数据
document.getElementById("selCity").options.length=1; //先清掉城市下拉框的的数据
$.getJSON("HandlerDropDownAjax.ashx",{"type":"city","fid":$(this).val()},function(data){
$.each(data, function(index, value) {
$("#selCity").append("<option value=&#39;" + value.value + "&#39;>" + value.text + "</option>");
});
});
});
//城市下拉框的值改变
$("#selCity").change(function(){
document.getElementById("selArea").options.length=1; //先清掉县下拉框的的数据
$.getJSON("HandlerDropDownAjax.ashx",{"type":"area","fid":$(this).val()},function(data){
$.each(data, function(index, value) {
$("#selArea").append("<option value=&#39;" + value.value + "&#39;>" + value.text + "</option>");
});
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<p>
三级联动:<select id="selProvince">
<option value="选择省份">==选择省份==</option>
</select> <select id="selCity"><option>==选择城市==</option></select>& amp;nbsp; <select id="selArea"><option>==选择县==</option></select>
</p>
</form>
</body>
</html>

asp.net part:

(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=&#39;" + fid + "&#39;";
      //构造数据的类型[{"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的作用是去掉最后一个&#39;逗号&#39;
    }
  }
  public bool IsReusable {
    get {
      return false;
    }
  }
}

The above is the detailed content of Detailed explanation of how Asp.Net+jQuery realizes the secondary linkage function of provinces and cities. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
C# and the .NET Runtime: How They Work TogetherC# and the .NET Runtime: How They Work TogetherApr 19, 2025 am 12:04 AM

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

C# .NET Development: A Beginner's Guide to Getting StartedC# .NET Development: A Beginner's Guide to Getting StartedApr 18, 2025 am 12:17 AM

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

C# and .NET: Understanding the Relationship Between the TwoC# and .NET: Understanding the Relationship Between the TwoApr 17, 2025 am 12:07 AM

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

The Continued Relevance of C# .NET: A Look at Current UsageThe Continued Relevance of C# .NET: A Look at Current UsageApr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

From Web to Desktop: The Versatility of C# .NETFrom Web to Desktop: The Versatility of C# .NETApr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C# .NET and the Future: Adapting to New TechnologiesC# .NET and the Future: Adapting to New TechnologiesApr 14, 2025 am 12:06 AM

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

Is C# .NET Right for You? Evaluating its ApplicabilityIs C# .NET Right for You? Evaluating its ApplicabilityApr 13, 2025 am 12:03 AM

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

C# Code within .NET: Exploring the Programming ProcessC# Code within .NET: Exploring the Programming ProcessApr 12, 2025 am 12:02 AM

The programming process of C# in .NET includes the following steps: 1) writing C# code, 2) compiling into an intermediate language (IL), and 3) executing by the .NET runtime (CLR). The advantages of C# in .NET are its modern syntax, powerful type system and tight integration with the .NET framework, suitable for various development scenarios from desktop applications to web services.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.