Question

I currently have a number of GridView tables on my site, but at the moment all sorting is done on the serving side, which isn't great due to the page refreshing. I've had a look into the [tablesorter][1] (jQuery) module which looks easy enough to use, but I can't get the thing to work. I've checked pretty much every link out there, but I have to admit, my level of knowledge is extremely basic. (Code created by someone else). Hopefully using a real example may help others to see how the client side sorting can be achieved. Below are the files I am working with as they stand without the tablesorter implementation. The .ascx file is:

    <%@ 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» -->

The .cs file behind is:

   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)
    {
    }
}

I have added the necessary jQuery / Tablesorter scripts into the head of the document. Any help appreciated.

Was it helpful?

Solution

In order to use tablesorter you have to put your data into a table. For asp.net websites you must add in the "thead tags" before your item template. Asp does not add these by default. The tags should contain a "tr" with all of your "th" inside. Then put a class on each table you want to sort, since you said you have lots of tables, give each of them a different class. Example:

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

And so on for all the tables. Now all of your tables should sort using the table sorter plugin. Hope this helps. I have been working with this alot on an asp website. If you ahve any questions pm me and I will try and help.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top