使用Ajax和Jquery实现GridView的展开、合并

本文来源:http://www.cnblogs.com/ywqu/archive/2009/09/06/1561420.html

需求简介:电子商务网站中,查询会员的订单,点击“會員”,展现此会员的订单列表。Demo

 

界面操作:

 

 

Step 1 展现会员列表,如下图

Step 2 点击“某一会员”行 展现会员订单列表

 

 实现思路:

1、 使用用户控件(CustomerOrders.ascx)展示订单列表,此用户控件只需要包含Repeater控件并绑定数据源

2、 新建一个简单页面GridViewDrillDownjQueryQAjax.aspx,在此页面引用用户控件,展示用户订单列表

3、 在页面GridViewDrillDownjQueryQAjax.aspx新建两个DIV:一个用来展示会员信息,一个用来展示某个会员的订单信息。当点击某一会员信息时,展示此会员的订单列表

实现细节:

1、 新建用户控件(CustomerOrders.ascx),拖数据源控件 Repeater控件到页面,主要代码如下

 在用户控件的后台代码中有一属性CustomerId,它主要用来传递参数

 

Codeasp:SqlDataSource ID="sqlDsOrders" runat="server" ConnectionString="<%$ ConnectionStrings:Northwind %>"
    SelectCommand
="SELECT [OrderID], [OrderDate], [RequiredDate], [Freight], [ShippedDate] FROM [Orders] WHERE ([CustomerID] = @CustomerID)">
    
<SelectParameters>
        
<asp:Parameter Name="CustomerID" Type="String" DefaultValue="" />
    
</SelectParameters>
</asp:SqlDataSource>
<asp:Repeater ID="List" DataSourceID="sqlDsOrders" runat="server">
    
<HeaderTemplate>
        
<table class="grid" cellspacing="0" rules="all" border="1" style="border-collapse: collapse;">
            
<tr>
                
<th scope="col">&nbsp;</th>
                
<th scope="col">Order ID</th>
                
<th scope="col">Date Ordered</th>
                
<th scope="col">Date Required</th>
                
<th scope="col" style="text-align: right;">Freight</th>
                
<th scope="col">Date Shipped</th>
            
</tr>
    
</HeaderTemplate>
    
<ItemTemplate>
        
<tr class='<%# (Container.ItemIndex%2==0) ? "row" : "altrow" %>'>
            
<td class="rownum"><%# Container.ItemIndex+1 %></td>
            
<td style="width: 80px;"><%Eval("OrderID"%></td>
            
<td style="width: 100px;"><%Eval("OrderDate","{0:dd/MM/yyyy}"%></td>
            
<td style="width: 110px;"><%Eval("RequiredDate""{0:dd/MM/yyyy}")%></td>
            
<td style="width: 50px; text-align: right;"><%Eval("Freight","{0:F2}"%></td>
            
<td style="width: 100px;"><%Eval("ShippedDate""{0:dd/MM/yyyy}")%></td>
        
</tr>
    
</ItemTemplate>
    
<FooterTemplate>
        
</table>
    
</FooterTemplate>
</asp:Repeater>

 

 

 

 2 重写用户控件(CustomerOrders.ascx)的OnLoad处理事件,代码如下:

Code override void OnLoad(EventArgs e)
    {
        
this.sqlDsOrders.SelectParameters["CustomerID"].DefaultValue = this.CustomerId;
        
base.OnLoad(e);
    }

 

 3、 新建一个简单页面GridViewDrillDownjQueryQAjax.aspx,在此页面引用用户控件(CustomerOrders.ascx),展示用户订单列表。下面的后台方法主要用来根据会员编号(CustomerId)获得会员的订单列表。

 

 

Codepublic static string GetOrders(string customerId)
    {
        System.Threading.Thread.Sleep(
500);
        Page page 
= new Page();
        CustomerOrders ctl 
= (CustomerOrders)page.LoadControl("~/CustomerOrders.ascx");
        ctl.CustomerId 
= customerId;
        page.Controls.Add(ctl);
        System.IO.StringWriter writer 
= new System.IO.StringWriter();
        HttpContext.Current.Server.Execute(page, writer, 
false);
        
string output = writer.ToString();
        writer.Close();
        
return output;
    }

以上3步主要完成的是后台代码,那么接下来我们需要做的是: 使用Ajax读取数据并折叠展示。

 

4、 在页面(GridViewDrillDownjQueryQAjax.aspx)新建两个Div 如下:

第一个Div用来展示会员信息,第二个Div用来展示此会员下的订单列表。当用点击会员信息时(第一个Div),初始化Ajax请求并返回html代码到第二个Div,展示此会员的订单列表。

Code<asp:GridView Width="100%" AllowPaging="True" ID="gvCustomers" AutoGenerateColumns="False"
                                            DataSourceID
="sqlDsCustomers" runat="server" ShowHeader="False">
                                            
<Columns>
                                                
<asp:TemplateField>
                                                    
<ItemTemplate>
                                                        
<div class="group" style="display:inline" id='<%#String.Format("customer{0}",Container.DataItemIndex) %>
                                                            onclick='showhide(
<%#String.Format("\"#customer{0}\"",Container.DataItemIndex) %>,
                                                                              
<%#String.Format("\"#order{0}\"",Container.DataItemIndex) %>,
                                                                              
<%#String.Format("\"{0}\"",Eval("CustomerID")) %>)'>
                                                            
<asp:Image ID="imgCollapsible" CssClass="first" ImageUrl="~/Assets/img/plus.png"
                                                                Style
="margin-right: 5px;" runat="server" /><span class="header">
                                                                    
<%#Eval("CustomerID")%>:
                                                                    
<%#Eval("CompanyName")%>(<%#Eval("TotalOrders")%> Orders) </span>
                                                        
</div>                                                        
                                                        
<div id='<%#String.Format("order{0}",Container.DataItemIndex) %>' class="order"></div>
                                                    
</ItemTemplate>
                                                
</asp:TemplateField>
                                            
</Columns>
                                        
</asp:GridView>

 

5、第一个Divi的客户端点击事件处理代码调用showhide(div1Id,div2Id,customerId)方法,主要代码如下:

Code showhide(master,detail,customerId)
            { 
                
//First child of master div is the image
                var src = $(master).children()[0].src;
                
//Switch image from (+) to (-) or vice versa.
                if(src.endsWith("plus.png"))
                    src 
= src.replace('plus.png','minus.png');
                
else
                    src 
= src.replace('minus.png','plus.png');
                
//if the detail DIV is empty Initiate AJAX Call, if not that means DIV already populated with data             
                if($(detail).html() == "")
                {
                    
//Prepare Progress Image
                    var $offset = $(master).offset();
                    $(
'#progress').css('visibility','visible');
                    $(
'#progress').css('top',$offset.top);
                    $(
'#progress').css('left',$offset.left+$(master).width());                    
                    
//Prepare Parameters
                    var params = '{customerId:"'+ customerId +'"}';                    
                    
//Issue AJAX Call
                    $.ajax({
                            type: 
"POST"//POST
                            url: "GridViewDrillDownjQueryAjax.aspx/GetOrders"//Set call to Page Method
                            data: params, // Set Method Params
                            beforeSend: function(xhr) {
                                xhr.setRequestHeader(
"Content-type""application/json; charset=utf-8");},
                            contentType: 
"application/json; charset=utf-8"//Set Content-Type
                            dataType: "json"// Set return Data Type
                            success: function(msg, status) {
                                $(
'#progress').css('visibility','hidden');
                                $(master).children()[
0].src = src;
                                $(detail).html(msg);
                                $(detail).slideToggle(
"normal"); // Succes Callback
                                },
                            error: 
function(xhr,msg,e){
                                alert(msg);
//Error Callback
                                }
                            });
                }
                
else
                {
                    
//Toggle expand/collapse                   
                    $(detail).slideToggle("normal");
                    $(master).children()[
0].src = src;
                }
            }

 

解释:

type: 请求方式使用“post

url:   请求的URL

data: 要传的参数

beforeSend:请求发送之前所要做的操作

contentType 设置contentTypeapplication/json; charset=utf-8

datatype: 设置返回类型为 json

success:请求成功返回正确的结果后 所要操作的事情,比如向第二个div追加订单列表html代码,然后滑动展示。

Error 请求失败,弹出失败信息

 

至此,使用AjaxJquery实现GridView的展开和合并完毕。

源代码下载:https://files.cnblogs.com/ywqu/GridViewDrillDownJQueryAjax.rar

 

英文地址:http://mosesofegypt.net/post/GridView-Grouping-Master-Detail-Drill-Down-Using-jQuery-AJAX.aspx

posted @ 2010-01-08 22:20  code_flyer  阅读(341)  评论(0编辑  收藏  举报