从GridView服务器端排序更改为客户端

时间:2012-08-20 14:30:15

标签: jquery asp.net gridview tablesorter gridview-sorting

我目前在我的网站上有许多GridView表,但目前所有的排序都在服务端完成,由于页面刷新,这不是很好。我已经看过[tablesorter] [1](jQuery)模块,它看起来很容易使用,但是我无法使用它。我已经检查了几乎每个链接,但我不得不承认,我的知识水平是非常基本的。 (由其他人创建的代码)。希望使用一个真实的例子可以帮助其他人看到如何实现客户端排序。下面是我正在使用的文件,因为它们没有tablesorter实现。 .ascx文件是:

    <%@ Control Language="C#" Inherits="List_PendingBids_Module" CodeFile="List_PendingBids.ascx.cs" %>
<!-- «Start| List: Pending bids» -->
<div class='pending-bids'>
  <h2>
    <span class="rightside">
      <%# App.Context.Team.GetAvailableCreditText() %>
    </span>
    My Pending Bids
  </h2>
  <div class="list">
    <asp:GridView runat="server" id="gridList" UseAccessibleHeader="true" AutoGenerateColumns="false" EnableViewState="false" GridLines="None"
    OnDataBinding="gridList_DataBinding" OnPageIndexChanging="List_PageIndexChanging" CssClass='grid' HeaderStyle-CssClass="header-row"
    OnRowCommand="gridList_RowCommand" AllowSorting="true" OnSorting="List_Sorting" AllowPaging="true" PageSize="15">
      <SelectedRowStyle CssClass="selected" />
      <AlternatingRowStyle CssClass="alt" />
      <FooterStyle CssClass="footer" />
      <EmptyDataRowStyle CssClass="empty-template" />
      <Columns>
        <asp:TemplateField  HeaderText="Name" HeaderStyle-CssClass="left-text" ItemStyle-CssClass="left-text" FooterStyle-CssClass="left-text" SortExpression="Name">
          <ItemTemplate>
            <asp:HyperLink runat="server" ID="btnItem_Player_Get_x_X_Name" Text='<%#Item.Player.Get(x => x.Name)%>' onclick='<%#"OpenModal(\"" + PageUrl("Player view > Details") + "?id=" + Item.Player.ID + "\");"%>' NavigateUrl="javascript:" />
          </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField  HeaderText="POS" SortExpression="Position.Abbreviation">
            <ItemTemplate>
              <asp:Literal ID="ltrPositionAbbreviation" runat="server" Text='<%#Server.HtmlEncode(Item.Player.Position.Abbreviation.ToStringOrEmpty())%>' />
            </ItemTemplate>
          </asp:TemplateField>
          <asp:TemplateField  HeaderText="Team" SortExpression="Club.NameAbbreviation">
            <ItemTemplate>
              <asp:Literal ID="ltrClubNameAbbreviation" runat="server" Text='<%#Server.HtmlEncode(Item.Player.Club.NameAbbreviation.ToStringOrEmpty())%>' />
            </ItemTemplate>
          </asp:TemplateField>
        <asp:TemplateField  HeaderText="Points" SortExpression="Player.SeasonScore">
          <ItemTemplate>
            <asp:Literal ID="ltrPlayerSeasonScore" runat="server" Text='<%#Item.Player.SeasonScore%>' />
          </ItemTemplate>
        </asp:TemplateField>

        <asp:TemplateField  HeaderText="Best Offer" HeaderStyle-CssClass="no-wrap" ItemStyle-CssClass="no-wrap" FooterStyle-CssClass="no-wrap" SortExpression="LowestSalePrice">
            <ItemTemplate>
              <span class="inline mid-width">
                §<%# LowestPricePlayerContractItem.Get(s=>s.SalePrice.ToString("n")) %>
              </span>
              <asp:LinkButton runat="server" ID="btnBuyNow" Visible='<%#LowestPricePlayerContractItem != null && App.Context.Team.CanSignPlayerInPosition(Item.Player.Position)%>' ToolTip="Buy Now" OnClientClick='<%#"if (confirm(\"Are you sure you want to buy this player? (If you have a bid pending for this player, remember to remove it - Transfer centre > Pending bids)\") == false) return false;" + SetPostBackCommandItem(Item)%>' CommandName="BuyNow" CommandArgument='<%#Item.Player.ID%>'>
                <asp:Image ID="Image1" runat="server" ImageUrl="/Images/RightGreenArrow.png"/>
              </asp:LinkButton>
            </ItemTemplate>
          </asp:TemplateField>

        <asp:TemplateField  HeaderText="Exceeds your budget">
          <ItemTemplate>
            <asp:Image runat="server" ID="btnExceedsYourBudget" Visible='<%#!Item.BuyerHasMoney%>' ImageUrl="/Images/Icons/coins.png" AlternateText="Exceeds your budget" />
          </ItemTemplate>
        </asp:TemplateField>

        <asp:TemplateField  HeaderText="Best Bid" SortExpression="Player.HighestBid">
          <ItemTemplate>
            <asp:Literal ID="ltrPlayerHighestBid" runat="server" Text='<%#"§{0:n2}".FormatWith(Item.Player.HighestBid.Get(h=>h.Price.ToString("n")))%>' />
          </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField  HeaderText="My bid" SortExpression="Price">
          <ItemTemplate>
            <asp:Literal ID="ltrPrice" runat="server" Text='<%#"§{0:n2}".FormatWith(Item.Price)%>' />
          </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField  HeaderText="Bid">
          <ItemTemplate>
            <asp:HyperLink runat="server" ID="btnReviseBid" ToolTip="Revise bid" onclick='<%#"OpenModal(\"" + PageUrl("Home > Transfers > My pending bids > Revise bid") + "?id=" + Item.ID + "\");"%>' NavigateUrl="javascript:">
              <asp:Image runat="server" ImageUrl="/Images/RightGreyArrow.png"/>
            </asp:HyperLink>
          </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField  HeaderText="Cancel Bid">
          <ItemTemplate>
            <asp:HoverButton runat="server" ID="btnCancelBid" ImageUrl="/Images/RedCard.png" AlternateText="Cancel bid" OnClientClick='<%#"if (confirm(\"Are you sure you want to cancel this bid?\") == false) return false;" + SetPostBackCommandItem(Item)%>' CommandName="CancelBid" CommandArgument='<%#Item.ID%>' />
          </ItemTemplate>
        </asp:TemplateField>
      </Columns>
      <PagerSettings Mode="NumericFirstLast" Position="Bottom"/>
      <PagerStyle CssClass="pager" />
      <EmptyDataTemplate>
        There is no bid to display.
      </EmptyDataTemplate>
    </asp:GridView>
  </div>
</div>
<!-- «End| List: Pending bids» -->

背后的.cs文件是:

   using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using App;
using Application.DataModel;
using Application.Model;

/// <summary>
/// Code behind of the module: List: Pending bids.
/// </summary>
public partial class List_PendingBids_Module : Application.UI.ListContainer<Bid>
{
    /// <summary>
    /// Gets the LowestPricePlayerContractItem property of this module.
    /// </summary>
    public PlayerContract LowestPricePlayerContractItem
    {
        get
        {
            return Item.Player.GetLowestPricePlayerContractFor(App.Context.Team);
        }
    }

    /// <summary>
    /// Raises the Init event of this control. It also sets up this module&#39;s state.
    /// </summary>
    /// <param name="e">The EventArgs instance containing the event data.</param>
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        if (!IsPostBack || SortExpression.IsEmpty())
        {
            ResetSortExpression("Date DESC");
        }
        // UpdatePagerMode
        gridList.UpdatePagerMode();
    }

    /// <summary>
    /// Raises the Load event of this module. It also loads the state of this module.
    /// </summary>
    /// <param name="e">The EventArgs instance containing the event data.</param>
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        PopulateList();
    }

    /// <summary>
    /// Gets a list of {0} used as the base data source for this list module.
    /// All sorting, filters, etc should be applied on this base source.
    /// </summary>
    /// <returns>A list of Bids that will be rendered on this module.</returns>
    protected override IEnumerable<Bid> GetBaseDataSource()
    {
        IEnumerable<Bid> result = App.Context.Team.Bids;
        result = result.Where(each => !each.Sold);

        return result;
    }

    /// <summary>
    /// Sorts the Bids in the data source of this module based on the current &#39;Sort Expression&#39; requested by the user.
    /// </summary>
    protected override void SortDataSource()
    {
        if (SortExpression.HasValue())
        {
            if (SortExpression == "Name")
            {
                _DataSource = _DataSource.OrderBy(item => item.Player.Get(x => x.Name));
            }
            else if (SortExpression == "Name DESC")
            {
                _DataSource = _DataSource.OrderByDescending(item => item.Player.Get(x => x.Name));
            }

            else if (SortExpression == "Player.SeasonScore")
            {
                _DataSource = _DataSource.OrderBy(item => item.Player.SeasonScore);
            }
            else if (SortExpression == "Player.SeasonScore DESC")
            {
                _DataSource = _DataSource.OrderByDescending(item => item.Player.SeasonScore);
            }

            else if (SortExpression == "Player.HighestBid")
            {
                _DataSource = _DataSource.OrderBy(item => item.Player.HighestBid);
            }
            else if (SortExpression == "Player.HighestBid DESC")
            {
                _DataSource = _DataSource.OrderByDescending(item => item.Player.HighestBid);
            }

            else if (SortExpression == "Date DESC")
            {
                // Order by "Date DESC"
                _DataSource = _DataSource.OrderByDescending(item => item.Date);
            }
            else
            {
                base.SortDataSource();
            }
        }
        else
        {
            // Order by "Date DESC"
            _DataSource = _DataSource.OrderByDescending(item => item.Date);
        }
    }

    /// <summary>
    /// Handles the RowCommand event of the list control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The GridViewCommandEventArgs instance containing the event data.</param>
    protected void gridList_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)
    {
        if (e.CommandName == "CancelBid")
        {
            var Item = GetSelectedItem();
            try
            {
                Database.Delete(Item);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }

            Reload();
        }

        if (e.CommandName == "BuyNow")
        {
            var Item = GetSelectedItem();

            double l_price;
            double ln_price;
            try
            {
                l_price = Item.Player.GetLowestPricePlayerContractFor(App.Context.Team).SalePrice.Value;
            }
            catch (Exception ex)
            {
                l_price = -1;
                // MessageBox.Show("No Contracts");
            }
            Item.Player.STLowestSalePrice = l_price;

            try
            {
                Item.Player.GetLowestPricePlayerContractFor(App.Context.Team).Perform(r => App.Context.Team.Buy(r));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }

            Response.Redirect(Request.RawUrl);
        }
    }



    /// <summary>
    /// Handles the DataBinding event of this list control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The EventArgs instance containing the event data.</param>
    protected void gridList_DataBinding(object sender, EventArgs e)
    {
    }
}

我已将必要的jQuery / Tablesorter脚本添加到文档的头部。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

要使用tablesorter,您必须将数据放入表中。对于asp.net网站,您必须在项目模板之前添加“thead标签”。 Asp默认不添加这些。标签应该包含一个“tr”,里面包含你所有的“th”。然后在每个要排序的表上放一个类,因为你说你有很多表,给每个表一个不同的类。例如:

<script>
 $('.table1').tablesorter();
 $('.table2').tablesorter();
 </script>

等等所有表格。现在,您的所有表都应该使用表分类器插件进行排序。希望这可以帮助。我一直在asp网站上使用这个很多。如果您对我有任何疑问,我会尽力帮助。