Paging and Sorting ListViews with ASP.NET MVC and jQuery using VB.NET

Introduction

This article provides a simple example of using jQuery along with the jQuery tablesorter and tablesorter.pager plug-ins to provide sorting and paging support for a listview within the context of an ASP.NET MVC application.  JQuery has partnered with Microsoft and is now integrated within the IDE to include the availability of intellisense support.  The article uses a C# MVC application as an example but all changes made to the example project were strictly limited to writing the markup and are as applicable to a VB.NET based MVC application as they are to C#.

1.gif

Figure 1: the NerdDinner MVC Application Modified with jQuery's Tablesorter and Pager

2.gif

Figure 2:  The live NerdDinner website with the original list of upcoming dinners

I used the NerdDinner tutorial project as the basis for this project:  http://www.nerddinner.com.   The original code and a preview of the pending MVC book authored by Hanselman, Guthrie, et al is available for download if you’d care to have a look; at present there does not appear to be a VB version of the project for those interested in that; even through the sample application is in C#, the only added code used on this project is in HTML so, if you are working on a VB based based MVC application, the actual markup discussed in this article is equally applicable to VB:

The source code is located here:  http://nerddinner.codeplex.com
The free e-book is available here:  http://tinyurl.com/aspnetmvc.

The original version of this project used the paged list approach to providing table paging; the original project did not include column sorting.  In modifying the project, I left in the existing code so that you can comment out or expose the original for comparison. 

Rather than using the paged list approach, this example uses jQuery along with the tablesorter and the tablesorter.pager plug-ins.  They both may be downloaded from this location:  http://tablesorter.com/.  jQuery itself, along with the documentation file needed to support intellisense, may be downloaded from here:  http://jquery.com/.

As for MVC, it and a growing number of sample applications and tutorials are available here:  http://www.asp.net/mvc/.

Getting Started

The download includes the modified NerdDinner MVC application; that MVC application is described in detail within the free e-book mentioned earlier.  Most of the implementation details with regards to creating a table that may be both paged and sorted with jQuery are pretty simple, one really need only add references to the JavaScript  files, the style sheet, and the graphics and add a little JavaScript to put it all together.

3.gif

Figure 3:  Added images and style sheets are placed in the Content Folder

I am not going to go into any details as to how the NerdDinner sample application works; that again is addressed in the e-book.  The controller and model code were not modified in anyway; all of the changes made to the original were made to the view used to show upcoming dinners.

4.gif

Figure 4:  Added JavaScript and Visual Studio Documentation Files

JQuery version 1.3.2 and the documentation file needed to support intellisense were added but are not necessary; the tablesorter and pager controls are added through the two JavaScript files shown in Figure 4 (jquery.tablesorter.js and jquery.tablesorter.pager.js); these files are necessary.

Figure 5 shows the overall NerdDinner solution; this solution is described in great detail in the free e-book mentioned at the beginning of this article.

5.gif

Figure 5:  Solution Explorer showing NerdDinner

The Code

There were no modifications to the NerdDinner solution code; all of the code necessary to support the addition of the tablesorter and pager plug-in was made within the markup and through the addition of the related JavaScript.

Code:  The Master Page.

In order to make use of the tablesorter and pager jQuery plug-ins, we need to reference the scripts in the master page; to that end, the following two lines were added to Site.Master.

  1.  <%--Added for Tablesorter and Pager--%>  
  2. <script src="/Scripts/jquery.tablesorter.js" type="text/javascript"></script>  
  3. <script src="/Scripts/jquery.tablesorter.pager.js"  
  4. type="text/javascript"></script> 
We also need to add the style sheet to the Site.Master:
  1. <link href="../../Content/style.css" rel="stylesheet" type="text/css" />  
Aside from the addition of these three lines, the Site.Master master page is in the original format as provided with the NerdDinner tutorial project.

Code:  The Index Page (index.aspx).

The index page is used to display the list of upcoming dinners within the context of the original NerdDinner project.  The entire content contained within the index page was left intact but commented out.  If you wanted to compare the two versions running, you can do so by commenting out the tablesorter related sections and by removing the commenting from the original parts.

The first bit to add to the index page was the JavaScript used to configure the tablesorter and pager plug-ins.  The annotation describes the settings used but in short I set the table to initially sort by sorting the first and seconds columns, both ascending.  The sortList argument is set to initially sort on one or more columns.  Column and direction are specified in a pair where the first value is the column and the second is the sort direction.  Specifying [0, 0] will result in an initial table sort based upon sorting column 0 in an ascending direction.  Specifying [ [ 0,0 ], [ 1,0 ]] will sort on the first and second columns, both in an ascending direction.

It should also be noted that the pager always defaults to show a page size of ten rows; since for work purposes I was interested in showing only five rows at a time and so I decided to set this table up to only show five rows upon display.  That is done with the pager's pagesize value (val) property and by calling change on the page size after setting the value (row count) argument.

The positionFixed property was set to false; this allows the pager to float such that it is always glued to the bottom of the table; if this is not set, the pager will appear in a fixed location regardless of the row count (e.g., with position fixed set to false, if the last page contains less rows, the pager will move up to the bottom of the table).

  1. <%--Configure Tablesorter and pager - script added to orginal  
  2.        NOTES:  
  3.        sortList: call tells sorter to initially sort on one or more  
  4.        columns [column,descending/ascending]  
  5.        in this example, we are telling it to sort the  
  6.        first column ascending and the second column ascending  
  7.        positionFixed: false keeps the pager locked to the bottom of  
  8.        the table regardless of the number of rows  
  9.        .pagesize: sets the number of rows visible.  If not set it will  
  10.        always default to ten rows (if we set the selected rows option to  
  11.        a lesser or greater value in the HTML.  In this case I changed it  
  12.        to 5 rows and then called change on it such that whenever the page  
  13.        loads it will initially only show five rows.  
  14.        #ListViewDinners is the list view control on this page; when rendered  
  15.        to the page it will be as a table and so we can control it with  
  16.        the tablesorter and pager through the assigned ID  
  17.    --%>  
  18.    <script type="text/javascript">  
  19.        $(document).ready(function() {  
  20.        $("#ListViewDinners").tablesorter({ widthFixed: true, sortList:  
  21.         [[0,0], [1,0]], widgets: ['zebra'] })  
  22.        .tablesorterPager({ container: $("#pager"), positionFixed: false });  
  23.        $(".pagesize").val("5");     
  24.        $(".pagesize").change();  
  25.    });  
  26.    </script> 
The next section of the markup creates a listview control and also binds the listview to an IQueryable collection of upcoming dinner dates.  You would likely not bind in this manner but would more likely create an object that we can bind the listview to in code and then add that object to the model.

Even though the listview is a server control and this is an MVC application, we can still use it.  When the control is rendered to the page it is provided as a normal table; we can still user the pager and tablesorter against it since the client-side JavaScript will operate on the rendered table; the only requirement is that the table ID matches that setup for the tablesorter.   Each section of the listview definition is described in the annotation but in general the objective is to define the table appearance, setup the table headers as anchors (so the tablesorter can pick off the column to sort on), and then to define the pager as the table footer.

  1.  <%--Replacement list based on the user of jquery, tablesorter and tablesorter.pager plugins  
  2. Since the tablesorter and pager operate on tables, you can use it against a listview control since the output is written out to the page as a table.  Just keep the ID synced with the ID passed to the table sorter and pager  
  3. Since we can bind the listview control, I, for this example, just bound the listview to the results returned by the dinner repository class FindUpcomingDinners call.  You could set it to a bindable set of results added to the model (in fact that is more likely what you will do in an MVC application.  
  4. --%>  
  5.         <%  
  6.             NerdDinner.Models.DinnerRepository dr = new  
  7.             NerdDinner.Models.DinnerRepository();  
  8.             ListViewDinners.DataSource = dr.FindUpcomingDinners();  
  9.             ListViewDinners.DataBind();  
  10.         %>  
  11.         <%--Define the table headers to work with the tablesorter  
  12. By defining the with an anchor tag and setting the column name  
  13.         --%>  
  14.         <asp:ListView runat="server" ID="ListViewDinners">  
  15.             <LayoutTemplate>  
  16.                 <table id="ListViewDinners" class="tablesorter">  
  17.                     <thead>  
  18.                         <tr>  
  19.                             <th>  
  20.                                 <a href="#">Title</a>  
  21.                             </th>  
  22.                             <th>  
  23.                                 <a href="#">Date</a>  
  24.                             </th>  
  25.                             <th>  
  26.                                 <a href="#">Time</a>  
  27.                             </th>  
  28.                         </tr>  
  29.                     </thead>  
  30.                     <tbody>  
  31.                         <tr id="itemPlaceholder" runat="server" />  
  32.                     </tbody>  
  33. <%--Define the pager within the table footer, set the button images and the page size options (the number of rows to show in the table). When setting the selected option, be sure to set the page size in the tablesorter related javascript - refer to the notes in the script block; if you don't set the value there, then regardless of what is placed into the selected pagesize option, the initial display of the grid will contain ten rows  
  34. --%>  
  35.                     <tfoot>  
  36.                         <tr id="pager">  
  37.                             <td colspan="7" style="border-right: solid 3px  
  38.     #7f7f7f;">  
  39.                                 <img src="../../Content/first.png"  
  40.           class="first" alt="First"/>  
  41.                                 <img src="../../Content/prev.png"  
  42.           class="prev" alt="Next"/>  
  43.                                 <input type="text" class="pagedisplay"/>  
  44.                                 <img src="../../Content/next.png"  
  45. class="next" alt="Next"/>  
  46.   <img src="../../Content/last.png"  
  47. class="last" alt="Last"/>  
  48.                                 <select class="pagesize">  
  49.                                     <option selected="selected"   
  50. value="5">5</option>  
  51.                                     <option value="10">10</option>  
  52.                                     <option value="15">15</option>  
  53.                                     <option  value="20">20</option>  
  54.                                 </select>  
  55.                             </td>  
  56.                         </tr>  
  57.                     </tfoot>                                   
  58.                 </table>  
  59.             </LayoutTemplate>  
  60.      <ItemTemplate>  
  61. <tr>  
  62. <%--An Html.ActionLink does not work here in this context because of the Evals (to get the dinner ID in this case), so roll your own hyperlink pointing the correct controller and action  
  63. --%>  
  64. <td><asp:HyperLink  NavigateUrl='<%#"/Dinners/Details/" + Eval("DinnerID").ToString() %>'ID="hl1" runat="server"><%#Eval("Title") %></asp:HyperLink></td>  
  65. <td><%# Convert.ToDateTime(Eval("EventDate")).ToShortDateString()%></td>  
  66. <td><%# Convert.ToDateTime(Eval("EventDate")).ToShortTimeString()%></td>                  
  67. </tr>  
  68. </ItemTemplate>  
  69. </asp:ListView> 
That is all there is to it; we can build and run the MVC application now and when we select the option to view upcoming dinners, those dinners will be presented within a listview control rendered to the page as a table.  Naturally we may also define standard tables and do the same sort of thing through the use of the plug-ins; likewise we can use other data sources including those loaded into the Model data.

Summary

The article shows an alternative approach to providing paging and sorting capabilities for a table within the context of an MVC application; the original version did not supply a sort option and it implemented a paged list to support paging through the controller and model code; this alternative provides both paging and sorting on the client-side.  
The example was built upon the NerdDinner tutorial MVC application and it was implemented without changing any of the code contained in that application.  This article demonstrates only two of the numerous plug-ins available through the use of jQuery within an MVC or standard ASP.NET website. 

As Microsoft has partnered with the folks at jQuery and as a result of that partnership, jQuery is now incorporated into Visual Studio along with intellisense documentation.


Similar Articles