用AjaxPro实现二级联动

来源:互联网 发布:知乎周刊怎么样 编辑:程序博客网 时间:2024/06/06 07:07

读过周公(http://blog.csdn.net/zhoufoxcn/)的一篇Blog(http://blog.csdn.net/zhoufoxcn/archive/2008/01/07/2029204.aspx)后,照着写了个示例

代码如下:

在实际asp.net项目中经常会遇到无刷新二级或者N级(N>=2)联动情况,其实N级联动和二级联动的原理都是一样的,实现这种办法有很多,一种是纯脚本实现(动态生成Array数组),一种 是采用微软的Ajax.net中的UpdatePanel来实现,今天我给大家来展示如何采用AjaxPro来实现,相关文章请参考http://blog.csdn.net/zhoufoxcn/archive/2008/01/05/2026908.aspx《AjaxPro与服务器端交互过程中如何传值》一文。

前台代码:Test.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Test.aspx.cs" Inherits="Test" %>

<!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>AjaxPro实现二级联动</title>
    
    
    
</head>
<body>
    
<form id="form1" runat="server">
    
<div>
    
    
<table width="200" border="0" align="center" cellpadding="3" cellspacing="1" bordercolor="#FFFFFF" style="border-collapse: collapse">
        
<tr align="center">
            
<td height="20" colspan="2">
                
<strong>AjaxPro实现二级联动</strong>
            
</td>
        
</tr>
        
<tr class="tdbg" >
            
<td style="width: 59px">
                省份
</td>
            
<td width="70%" align="left">
                
<asp:DropDownList ID="ddlProvince" runat="server" DataTextField="ProvinceName" DataValueField="ProvinceID">
                
</asp:DropDownList>
            
</td>
        
</tr>
        
<tr class="tdbg" >
            
<td style="width: 59px"><strong>城市</strong></td>
            
<td align="left">
                
<asp:DropDownList ID="ddlCity" runat="server">
                
</asp:DropDownList>
            
</td>
        
</tr>
    
</table>
        
<br />
        奈奈就是俺,以上局部刷新不会影响到俺,因为整个页面是不刷新的,嘿嘿!
    
</div>
    
    
<script type="text/javascript" language="javascript" defer="defer">
        
function showCity(provinceId)
        {
              
var res = Test.getCityList(provinceId).value;
              
              
var ddlCity = document.getElementById("<%=ddlCity.UniqueID %>");
              ddlCity.length 
= 0;
              
              
if(res)
              {
                    
//res是服务器返回的一个List<City>集合
                    for(var i=0; i<res.length; i++)
                    {
                        ddlCity.options.add(
new Option(res[i].CityName,res[i].CityId));
                        
//从上面可以看出可以直接调用List<City>集合中的元素和它们的属性
                    }
              } 
        }
    
</script>
    
    
</form>
</body>
</html>

后台代码:Test.aspx.cs,注意为了省事,把实体类也一同归并到一个.cs文件中了。

数据库中建了2个表,分别为 Province 与 City

 表 Province 的字段为:ProvinceID、ProvinceName

表  的字段为:CityID、ProvinceID、CityName

(写的够详细啦,原本可以不写的)

 

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
/**
 * 参照周公的Blog
 * 写作说明:本文展示了如何利用AjaxPro与服务器交互,并且还展示了在JS中可以直接调用服务器方法返回集合
 * 作者:奈奈
 * 日期:2008-1-10
 * 首发地址:
http://blog.csdn.net/mndn_nana/
 *
*/

public partial class Test : System.Web.UI.Page
{
    
protected void Page_Load(object sender, EventArgs e)
    {
        AjaxPro.Utility.RegisterTypeForAjax(
typeof(Test));
        
        
if(!this.IsPostBack)
        {
            databind_ddlProvince();

            ddlProvince.Attributes[
"onchange"= "javascript:showCity(this.options[this.selectedIndex].value);";//注册ajaxPro,括号中的参数是当前的类名
        }        
    }
    
    
private void databind_ddlProvince()
    {
        
string strConnection = System.Configuration.ConfigurationManager.AppSettings["ConnectionString"];
        SqlConnection con 
= new SqlConnection(strConnection);
        SqlDataAdapter sda 
= new SqlDataAdapter("select * from Province", con);
        DataSet ds 
= new DataSet();
        con.Open();
        sda.Fill(ds,
"tbProvince");
        con.Close();

        ddlProvince.DataSource 
= ds;
        ddlProvince.DataValueField 
= "ProvinceID";
        ddlProvince.DataTextField 
= "ProvinceName";
        ddlProvince.DataBind();
    }

    [AjaxPro.AjaxMethod]
//申明是ajaxPro方法
    public List<City> getCityList(int provinceId)
    {
        
string strConnection = System.Configuration.ConfigurationManager.AppSettings["ConnectionString"];
        SqlConnection con 
= new SqlConnection(strConnection);
        SqlDataAdapter sda 
= new SqlDataAdapter("select * from City where ProvinceID=" + provinceId, con);
        DataSet ds 
= new DataSet();
        con.Open();
        sda.Fill(ds, 
"tbCity");
        con.Close();

        List
<City> tempList = new List<City>();
        
for(int i=0; i<ds.Tables["tbCity"].Rows.Count; i++)
        {   
            tempList.Add(
new City(Convert.ToInt32(ds.Tables["tbCity"].Rows[i]["CityID"]), Convert.ToString(ds.Tables["tbCity"].Rows[i]["CityName"]), provinceId));   
        }
        
return tempList;
    }

/// <summary>
/// 城市信息
/// </summary>
    public class City
    {
        
private int _cityId;
        
private int _stateId;
        
private string _cityName;
        
/// <summary>
        
/// 城市名称
        
/// </summary>
        public string CityName
        {
            
get { return _cityName; }
            
set { _cityName = value; }
        }

        
/// <summary>
        
/// 城市所在省份编号
        
/// </summary>
        public int StateId
        {
            
get { return _stateId; }
            
set { _stateId = value; }
        }

        
/// <summary>
        
/// 城市编号
        
/// </summary>
        public int CityId
        {
            
get { return _cityId; }
            
set { _cityId = value; }
        }

        
public City(int cityId, string cityName, int stateId)
        {
            
this._cityId = cityId;
            
this._cityName = cityName;
            
this._stateId = stateId;
        }
    }

}

 

程序运行效果:


未选择的效果:

选择河南的效果:

选择奈奈的家乡山西太原的效果:

具体代码很简单,也做了注释,如果还是不懂,请看周公的另一篇文章(http://blog.csdn.net/zhoufoxcn/archive/2008/01/05/2026908.aspx)吧。