坐峰怀雪灬

路漫漫其修远兮,吾将上下而求索。
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Ajax省市区无刷新单表联动查询

Posted on 2016-11-24 13:14  坐峰怀雪灬  阅读(477)  评论(0编辑  收藏  举报

方法一:

在很多时候都需要用到无刷新级联查询,本文将以省市区的级联查询作为例子。注:此为单表三级联动

环境:Vistual Studio 2015 、MSSQL

1、首先下载AjaxControlToolkit控件,附件下载地址附文章末尾。

2、创建Asp.net网站,将AjaxControlToolkit.dll和AjaxControlToolkit.pdb拷至项目的Bin文件夹下,并在项目中引用。

3、在Web.config配置文件中<system.web> 中添加如下节点

1 <pages controlRenderingCompatibilityVersion="4.0" clientIDMode="AutoID">
2             <controls>
3                 <add tagPrefix="webdiyer" namespace="Wuqi.Webdiyer" assembly="AspNetPager"/>
4                 <add tagPrefix="web" namespace="WebChart" assembly="WebChart"/>
5                 <add tagPrefix="web" namespace="EeekSoft.Web" assembly="EeekSoft.Web.PopupWin"/>
6                 <add tagPrefix="ajax" namespace="AjaxControlToolkit" assembly="AjaxControlToolkit"/>
7             </controls>
8  </pages>

4、配置完成后前台页面写代码(写在form标签内)

 1   <div>
 2             <asp:ScriptManager ID="ScriptManager1" runat="server">
 3             </asp:ScriptManager>
 4             <div>
 5                 <asp:UpdatePanel ID="UpdatePanel1" runat="server">
 6                     <ContentTemplate>
 7                         <asp:DropDownList ID="ddlProvince" runat="server">
 8                         </asp:DropDownList>
 9                         <asp:DropDownList ID="ddlCity" runat="server">
10                         </asp:DropDownList>
11                         <asp:DropDownList ID="ddlDistrict" runat="server">
12                         </asp:DropDownList>
13                         <ajax:cascadingdropdown id="CascadingDropDown1_Province" runat="server" targetcontrolid="ddlProvince"
14                             servicepath="CityService.asmx" servicemethod="GetProvince" category="ProvinceID"
15                             prompttext="请选择省份" loadingtext="省份加载中..."></ajax:cascadingdropdown>
16                         <ajax:cascadingdropdown id="CascadingDropDown1_City" runat="server" servicepath="CityService.asmx"
17                             servicemethod="GetCity" targetcontrolid="ddlCity" parentcontrolid="ddlProvince" prompttext="请选择城市" loadingtext="城市加载中..."
18                             category="CityID"></ajax:cascadingdropdown>
19                         <ajax:cascadingdropdown id="CascadingDropDown1_District" runat="server" servicepath="CityService.asmx"
20                             servicemethod="GetDistrict" targetcontrolid="ddlDistrict" parentcontrolid="ddlCity" category="DistrictID"
21                             prompttext="请选择区" loadingtext="区加载中..."></ajax:cascadingdropdown>
22                     </ContentTemplate>
23                 </asp:UpdatePanel>
24             </div>
25         </div>

5、在项目中新建一个Web服务(本例命名为:CityService.asmx)

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.Services;
 6 using System.Data.SqlClient;  //引用
 7 using System.Data;
 8 using AjaxControlToolkit;  //引用AjaxContrlToolkit控件
 9 using System.Collections.Specialized;//引用
10 /// <summary>
11 ///CityService 的摘要说明
12 /// </summary>
13 [WebService(Namespace = "http://tempuri.org/")]
14 [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
15 //若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。 
16 [System.Web.Script.Services.ScriptService]  //需要把些标记加上,不然调不到方法
17 public class CityService : System.Web.Services.WebService
18 {
19 
20     public CityService()
21     {
22         //如果使用设计的组件,请取消注释以下行 
23         //InitializeComponent(); 
24     }
25     static string ConnStr = "Server=10.72.25.12;User ID=zzcp;Password=gwbnsh@zzcp;database=zzcp;Connection Reset=FALSE";
26     /// <summary>
27     /// 获取省份
28     /// </summary>
29     /// <param name="knownCategoryValues"></param>
30     /// <param name="category"></param>
31     /// <returns></returns>
32     [WebMethod]
33     public CascadingDropDownNameValue[] GetProvince(string knownCategoryValues, string category)
34     {
35         List<CascadingDropDownNameValue> list = new List<CascadingDropDownNameValue>(); SqlConnection conn = new SqlConnection(ConnStr);
36         string sql = "SELECT * FROM tb_regions WHERE LevelType=1";
37         conn.Open();
38         SqlCommand cmd = new SqlCommand(sql, conn);
39         SqlDataReader dr = cmd.ExecuteReader();
40         while (dr.Read())
41         {
42             CascadingDropDownNameValue t = new CascadingDropDownNameValue(dr["Name"].ToString(), dr["id"].ToString());
43             list.Add(t);
44         }
45         dr.Close();
46         conn.Close();
47         return list.ToArray();
48     }
49     /// <summary>
50     /// 获取城市
51     /// </summary>
52     /// <param name="knownCategoryValues"></param>
53     /// <param name="category"></param>
54     /// <returns></returns>
55     [WebMethod]
56     public CascadingDropDownNameValue[] GetCity(string knownCategoryValues, string category)
57     {
58         SqlConnection conn = new SqlConnection(ConnStr);
59         List<CascadingDropDownNameValue> list = new List<CascadingDropDownNameValue>();
60         StringDictionary sd = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
61         string sql = string.Format("SELECT * FROM tb_regions WHERE LevelType=2 AND ParentId='{0}' ", sd["ProvinceID"]);
62         conn.Open();
63         SqlCommand cmd = new SqlCommand(sql, conn);
64         SqlDataReader dr = cmd.ExecuteReader();
65         while (dr.Read())
66         {
67             CascadingDropDownNameValue t = new CascadingDropDownNameValue(dr["Name"].ToString(), dr["id"].ToString());
68             list.Add(t);
69         }
70         dr.Close();
71         conn.Close();
72         return list.ToArray();
73     }
74     /// <summary>
75     /// 获取区
76     /// </summary>
77     /// <param name="knownCategoryValues"></param>
78     /// <param name="category"></param>
79     /// <returns></returns>
80     [WebMethod]
81     public CascadingDropDownNameValue[] GetDistrict(string knownCategoryValues, string category)
82     {
83         SqlConnection conn = new SqlConnection(ConnStr);
84         List<CascadingDropDownNameValue> list = new List<CascadingDropDownNameValue>();
85         StringDictionary sd = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
86         string sql = string.Format("SELECT * FROM tb_regions WHERE LevelType=3 AND ParentId='{0}' ", sd["CityID"]);
87         conn.Open();
88         SqlCommand cmd = new SqlCommand(sql, conn);
89         SqlDataReader dr = cmd.ExecuteReader();
90         while (dr.Read())
91         {
92             CascadingDropDownNameValue t = new CascadingDropDownNameValue(dr["Name"].ToString(), dr["id"].ToString());
93             list.Add(t);
94         }
95         dr.Close();
96         conn.Close();
97         return list.ToArray();
98     }
99 }

CascadingDropDown与DropDownList控件组合,下面是对其各个属性的一个简单说明:

  • TargetControlID:与之协作的DropDownList控件的ID。
  • ParentControlID:父级下拉框的ID,显然顶级下拉框ddlProvince不含有父级下拉框,因此不含有ParentControlID。
  • Category:此下拉框的“类别”,也可以称为名称,具体使用到后面再说,这里说了也不好理解。
  • PromptText:进行选择之前显示的文本。
  • LoadingText:加载时显示的文本,因为需要与服务端进行通信,所以难免会产生延迟,这里的文本便是在延迟时显示的文本。
  • ServicePath:获取数据时的Web服务。此处即为我们的WCF服务。
  • ServiceMethod:获取数据的方法。这些方法由WCF服务实现,显然我们暂时并没有实现它。

方法二:

前台代码:

 1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Douyu.Default" %>
 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     <title></title>
 9 </head>
10 <body>
11     <form id="form1" runat="server">
12     <div>
13    <asp:ScriptManager ID="ScriptManager1" runat="server">  
14 </asp:ScriptManager>  
15 <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
16     <ContentTemplate>  
17         <asp:DropDownList ID="ddlProvice" runat="server" AppendDataBoundItems="true" AutoPostBack="true"  
18             OnSelectedIndexChanged="ddlProvice_SelectedIndexChanged">  
19             <asp:ListItem Text="-请选择省份-" Value=""></asp:ListItem>  
20         </asp:DropDownList>  
21         <asp:DropDownList ID="ddlCity" runat="server" AutoPostBack="true"  
22             onselectedindexchanged="ddlCity_SelectedIndexChanged">  
23             <asp:ListItem Text="-请选择城市-" Value=""></asp:ListItem>  
24         </asp:DropDownList>  
25         <asp:DropDownList ID="ddlArea" runat="server">  
26             <asp:ListItem Text="-请选择县区-" Value=""></asp:ListItem>  
27         </asp:DropDownList>  
28     </ContentTemplate>  
29 </asp:UpdatePanel>  
30     </div>
31     </form>
32 </body>
33 </html>

后台代码:

 1 using GwbnshHD;
 2 using System;
 3 using System.Collections.Generic;
 4 using System.Data;
 5 using System.Linq;
 6 using System.Web;
 7 using System.Web.UI;
 8 using System.Web.UI.WebControls;
 9 
10 namespace Douyu
11 {
12     public partial class Default : System.Web.UI.Page
13     {
14         protected void Page_Load(object sender, EventArgs e)
15         {
16             if (!IsPostBack)
17             {
18                 BindProvince();
19                 BindCity();
20                 BindDistrict();
21             }
22         }
23         //加载城市  
24         protected void ddlProvice_SelectedIndexChanged(object sender, EventArgs e)
25         {
26             BindCity();
27             BindDistrict();
28         }
29         //加载县区  
30         protected void ddlCity_SelectedIndexChanged(object sender, EventArgs e)
31         {
32             BindDistrict();
33         }
34         //加载省份  
35         protected void BindProvince()
36         {
37             DataTable dt = DbHelperSQL.Query("SELECT * FROM tb_regions WHERE LevelType=1").Tables[0];
38             ddlProvice.DataTextField = "Name";
39             ddlProvice.DataValueField = "id";
40             ddlProvice.DataSource = dt;
41             ddlProvice.DataBind();
42         }
43         /// <summary>
44         /// 绑定市区
45         /// </summary>
46         /// <param name="code"></param>
47         public void BindCity()
48         {
49             string SelectPro = ddlProvice.SelectedValue;
50             if (!string.IsNullOrEmpty(SelectPro))
51             {
52                 ddlCity.Items.Clear();
53                 ddlCity.AppendDataBoundItems = true;
54                 ddlCity.Items.Insert(0, new ListItem("-请选择城市-", ""));
55                 DataTable dt1 = DbHelperSQL.Query("SELECT * FROM tb_regions WHERE LevelType=2 AND ParentId=" + SelectPro + "").Tables[0];
56                 ddlCity.DataTextField = "Name";
57                 ddlCity.DataValueField = "id";
58                 ddlCity.DataSource = dt1;
59                 ddlCity.DataBind();
60             }
61             else
62             {
63                 ddlCity.Items.Clear();
64                 ddlCity.AppendDataBoundItems = true;
65                 ddlCity.Items.Insert(0, new ListItem("-请选择城市-", ""));
66             }
67         }
68         /// <summary>
69         /// 绑定县区
70         /// </summary>
71         /// <param name="code"></param>
72         public void BindDistrict()
73         {
74             string SelectCity = ddlCity.SelectedValue;
75             if (!string.IsNullOrEmpty(SelectCity))
76             {
77                 ddlArea.Items.Clear();
78                 ddlArea.AppendDataBoundItems = true;
79                 ddlArea.Items.Insert(0, new ListItem("-请选择县区-", ""));
80                 DataTable dt2 = DbHelperSQL.Query("SELECT * FROM tb_regions WHERE LevelType=3 AND ParentId=" + SelectCity + "").Tables[0];
81                 ddlArea.DataTextField = "Name";
82                 ddlArea.DataValueField = "id";
83                 ddlArea.DataSource = dt2;
84                 ddlArea.DataBind();
85             }
86             else
87             {
88                 ddlArea.Items.Clear();
89                 ddlArea.AppendDataBoundItems = true;
90                 ddlArea.Items.Insert(0, new ListItem("-请选择县区-", ""));
91             }
92         }
93     }
94 }

 

数据库SQL文件:附加下载

AjaxControlToolkit控件:附件下载