Ajax實現二級(多級)聯動——Asp.Net


  下拉標簽的聯動功能在網站開發中很常見,也是網站開發中必備的基本技能。WebForm中僅用DropDownList就可以輕易地實現下拉框的聯動功能,但是太局限。MVC的日益強大,傳統的WebForm組件就變得不是很實用。所以想要隨着時代的腳步前進,掌握新的技能尤為重要。下面就自己通過Ajax實現聯動的過程與大家分享。

 

1.前台代碼:

 1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ShowAjax.aspx.cs" Inherits="Ajax_Test.Pages.ShowAjax" %>
 2 
 3 <!DOCTYPE html>
 4 
 5 <html xmlns="http://www.w3.org/1999/xhtml">
 6     <head runat="server">
 7     <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 8     <script src="../JS/jquery-3.1.1/jquery-3.1.1/jquery-3.1.1.min.js"></script>
 9     <script src="../JS/ajax_test.js"></script>
10     <title></title>
11     </head>
12     <body>
13         <form id="form1" runat="server">
14             <div>
15 
16              <select id="pro_c" name="pro_c" onchange="Pro_Change()">
17                 <option>---請選擇---</option>
18              </select>
19 
20              <select id="city_c" name="city_c">
21                 <option>---請選擇---</option>
22              </select>
23 
24             </div>
25         </form>
26     </body>
27 </html>

 

2.JS代碼:

 1 $(document).ready(function () {
 2     $.ajax({
 3         timeout: 3000,
 4         async: false,
 5         type: "POST",
 6         url: "GetPro.ashx",
 7         dataType: "json",
 8         data: {
 9             pro: $("#pro_c").val(),
10         },
11         success: function (data) {
12             for (var i = 0; i < data.length; i++) {
13                 $("#pro_c").append("<option>" + data[i].Name + "</option>");
14             }
15         }
16     });
17 });
18 
19 
20 
21 
22 function Pro_Change()
23 {
24     $("#city_c").empty();
25 
26     $("#city_c").append("<option>---請選擇---</option>");
27 
28     var pro = document.getElementById("pro_c").value;
29 
30     console.log(pro);
31 
32     $.ajax({
33         timeout: 3000,
34         async: false,
35         type: "POST",
36         url: "GetCity.ashx",
37         dataType: "json",
38         data: {
39             getpro: pro,
40         },
41         success: function (data) {
42             for (var i = 0; i < data.length; i++) {
43                 $("#city_c").append("<option>" + data[i].Name + "</option>");
44             }
45         }
46     });
47 }

 

3.一般處理程序

  (1)查詢一級下拉菜單的所有內容並轉化為Json數據

 1 using Ajax_Test.DataCenter;
 2 using System;
 3 using System.Collections.Generic;
 4 using System.Data;
 5 using System.Linq;
 6 using System.Text;
 7 using System.Web;
 8 
 9 namespace Ajax_Test.Pages
10 {
11     /// <summary>
12     /// GetPro 的摘要說明
13     /// </summary>
14     public class GetPro : IHttpHandler
15     {
16 
17         public bool IsReusable
18         {
19             get
20             {
21                 throw new NotImplementedException();
22             }
23         }
24 
25         /// <summary>
26         /// 將得到的table轉化為Json
27         /// </summary>
28         /// <param name="table"></param>
29         /// <returns></returns>
30         public string toJson(DataTable table)
31         {
32             StringBuilder json = new StringBuilder();
33 
34             if (table == null)
35             {
36                 return "null";
37 
38             }
39 
40             json.Append("[");
41             foreach (DataRow row in table.Rows)
42             {
43                 json.Append("{\"Name\":\"");
44                 json.Append(row["ProName"]);
45                 json.Append("\"},");
46             }
47 
48             return json.ToString().Substring(0, json.ToString().LastIndexOf(",")) + "]";
49         }
50 
51 
52         /// <summary>
53         /// 查詢一級下拉菜單的內容
54         /// </summary>
55         /// <param name="context"></param>
56         public void ProcessRequest(HttpContext context)
57         {
58 
59             DoSomething sth = new DoSomething();
60 
61             DataTable table = new DataTable();
62 
63             table = sth.SelectPro();
64 
65             string json = toJson(table);
66 
67             context.Response.ContentType = "text/plain";
68 
69             context.Response.Write(json);
70 
71         }
72     }
73 }

 

  

 

  (2)通過選擇的一級下拉菜單內容查詢得到二級下拉菜單的內容並轉化為Json數據

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using Ajax_Test.DataCenter;
 6 using System.Text;
 7 using System.Data;
 8 
 9 namespace Ajax_Test.Pages
10 {
11     /// <summary>
12     /// GetCity 的摘要說明
13     /// </summary>
14     public class GetCity : IHttpHandler
15     {
16         public bool IsReusable
17         {
18             get
19             {
20                 throw new NotImplementedException();
21             }
22         }
23 
24         /// <summary>
25         /// 將得到的table轉化為Json
26         /// </summary>
27         /// <param name="table"></param>
28         /// <returns></returns>
29         public string toJson(DataTable table)
30         {
31             StringBuilder json = new StringBuilder();
32 
33             if (table == null)
34             {
35                 return "null";
36 
37             }
38 
39             json.Append("[");
40             foreach (DataRow row in table.Rows)
41             {
42                 json.Append("{\"Name\":\"");
43                 json.Append(row["CityName"]);
44                 json.Append("\"},");
45             }
46 
47             
48 
49             return json.ToString().Substring(0, json.ToString().LastIndexOf(",")) + "]";
50         }
51 
52 
53         /// <summary>
54         /// 通過選擇的一級下拉菜單內容查詢得到二級下拉菜單的內容
55         /// </summary>
56         /// <param name="context"></param>
57         public void ProcessRequest(HttpContext context)
58         {
59 
60             string pro = context.Request.Form["getpro"];
61 
62             if (pro == "---請選擇---")
63             {
64                 return;
65             }
66 
67             DoSomething sth = new DoSomething();
68 
69             DataTable table = new DataTable();
70 
71             table = sth.SelectCity(pro);
72 
73             string json = toJson(table);
74 
75             context.Response.ContentType = "text/plain";
76 
77             context.Response.Write(json);
78         }
79     }
80 }

 

4.數據交互代碼:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Data;
 4 using System.Data.SqlClient;
 5 using System.Linq;
 6 using System.Web;
 7 
 8 namespace Ajax_Test.DataCenter
 9 {
10     public class DoSomething
11     {
12         string connectionString = "Data Source=K14FPTKA5UMAE69;Initial Catalog=ProTable;Integrated Security=True";
13 
14         SqlConnection conn;
15 
16         /// <summary>
17         /// 查詢出所有的省份信息
18         /// </summary>
19         /// <returns></returns>
20         public DataTable SelectPro()
21         {
22             string sql = "select * from Pro";
23 
24             using (conn = new SqlConnection(connectionString))
25             {
26                 conn.Open();
27 
28                 SqlDataAdapter da = new SqlDataAdapter(sql,conn);
29 
30                 DataSet ds = new DataSet();
31 
32                 da.Fill(ds);
33 
34                 return ds.Tables[0];
35             }
36         }
37 
38 
39         public DataTable SelectCity(string pro)
40         {
41             DataTable table = new DataTable();
42 
43             table.Columns.Add(new DataColumn("CityName"));
44 
45             string sql = "select * from City where ProName = @pro ";
46 
47             SqlParameter[] parameter = { new SqlParameter("pro",pro)};
48 
49             using (conn = new SqlConnection(connectionString))
50             {
51                 SqlCommand com = new SqlCommand(sql,conn);
52 
53                 try
54                 {
55                     if (parameter != null)
56                     {
57                         foreach (SqlParameter sqlP in parameter)
58                         {
59                             com.Parameters.Add(sqlP);
60                         }
61                     }
62                     conn.Open();
63 
64                     SqlDataReader reader = com.ExecuteReader();
65 
66                     while (reader.Read())
67                     {
68                         DataRow row = table.NewRow();
69 
70                         row["CityName"] = reader["CityName"];
71 
72                         table.Rows.Add(row);
73 
74                     }
75                 } catch (Exception e)
76                 {
77                     table = null;
78                 }
79 
80                 return table;
81             }
82         }
83     }
84 }

 

 

  具體實現過程:頁面加載時,Ajax請求通過一般處理程序獲得並初始化一級下拉菜單的內容。選定一級下拉菜單內容時,觸發select標簽的onchange方法,在JS中進行第二次Ajax請求,同樣,通過一般處理程序獲得並初始化二級下拉菜單的內容。(JS中,Ajax請求成功返回的Json數據是通過append方法附加到相應的select標簽的,所以制作二級下拉菜單的過程中遇到一些小插曲。每改變一次一級下拉菜單的內容,都會附加一次數據到二級下拉菜單,二級下拉菜單中的內容會越來越多而且重復,所以在向二級下拉菜單附加數據之前須先清除二級下拉菜單已經擁有的所有option,jQuery為我們提供了$("#name").empty()方法)數據交互則是ADO.NET的相關知識,在前面有詳細的介紹,在此就不再贅述。簡單幾步,一個Ajax實現下拉標簽聯動的demo就完成了,在二級聯動的基礎上,為后續的select標簽添加onchange方法並進行新的Ajax請求,就是一個多級聯動的實現。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM