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请求,就是一个多级联动的实现。

原文地址:https://www.cnblogs.com/SunshineAgain/p/6068363.html