Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » ASP.NET & Web Forms » Paging and Sorting ListViews with ASP.NET MVC and jQuery

Paging and Sorting ListViews with ASP.NET MVC and jQuery

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.

Author Rank:
Total page views :  14829
Total downloads :  454
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
NerdDinner 1.0.zip
 
Become a Sponsor


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.

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:

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.

<%--Added for Tablesorter and Pager--%>

<script src="/Scripts/jquery.tablesorter.js" type="text/javascript"></script>

<script src="/Scripts/jquery.tablesorter.pager.js"

type="text/javascript"></script>

We also need to add the style sheet to the Site.Master:

<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).

<%--Configure Tablesorter and pager - script added to orginal

        NOTES:

       

        sortList: call tells sorter to initially sort on one or more

        columns [column,descending/ascending]

        in this example, we are telling it to sort the

        first column ascending and the second column ascending

       

        positionFixed: false keeps the pager locked to the bottom of

        the table regardless of the number of rows

       

        .pagesize: sets the number of rows visible.  If not set it will

        always default to ten rows (if we set the selected rows option to

        a lesser or greater value in the HTML.  In this case I changed it

        to 5 rows and then called change on it such that whenever the page

        loads it will initially only show five rows.

       

        #ListViewDinners is the list view control on this page; when rendered

        to the page it will be as a table and so we can control it with

        the tablesorter and pager through the assigned ID

    --%>

    <script type="text/javascript">

        $(document).ready(function() {

        $("#ListViewDinners").tablesorter({ widthFixed: true, sortList:

         [[0,0], [1,0]], widgets: ['zebra'] })

        .tablesorterPager({ container: $("#pager"), positionFixed: false });

        $(".pagesize").val("5");   

        $(".pagesize").change();

    });

    </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.

<%--Replacement list based on the user of jquery, tablesorter and tablesorter.pager plugins        

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         

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.

--%>

        <%

            NerdDinner.Models.DinnerRepository dr = new

            NerdDinner.Models.DinnerRepository();

            ListViewDinners.DataSource = dr.FindUpcomingDinners();

            ListViewDinners.DataBind();

        %>

        <%--Define the table headers to work with the tablesorter

By defining the with an anchor tag and setting the column name

        --%>

        <asp:ListView runat="server" ID="ListViewDinners">

            <LayoutTemplate>

                <table id="ListViewDinners" class="tablesorter">

                    <thead>

                        <tr>

                            <th>

                                <a href="#">Title</a>

                            </th>

                            <th>

                                <a href="#">Date</a>

                            </th>

                            <th>

                                <a href="#">Time</a>

                            </th>                          

                        </tr>

                    </thead>

                    <tbody>

                        <tr id="itemPlaceholder" runat="server" />

                    </tbody>

 

 

 

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

--%>           

                    <tfoot>

                        <tr id="pager">

                            <td colspan="7" style="border-right: solid 3px

    #7f7f7f;">

                                <img src="../../Content/first.png"

          class="first" alt="First"/>

                                <img src="../../Content/prev.png"

          class="prev" alt="Next"/>

                                <input type="text" class="pagedisplay"/>

                                <img src="../../Content/next.png"

class="next" alt="Next"/>

  <img src="../../Content/last.png"

class="last" alt="Last"/>

                                <select class="pagesize">

                                    <option selected="selected" 

value="5">5</option>

                                    <option value="10">10</option>

                                    <option value="15">15</option>

                                    <option  value="20">20</option>

                                </select>

                            </td>

                        </tr>

                    </tfoot>                                 

                </table>

            </LayoutTemplate>

     <ItemTemplate>

<tr>

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

--%>

<td><asp:HyperLink  NavigateUrl='<%#"/Dinners/Details/" + Eval("DinnerID").ToString() %>' ID="hl1" runat="server"><%#Eval("Title") %></asp:HyperLink></td>

<td><%# Convert.ToDateTime(Eval("EventDate")).ToShortDateString()%></td>

<td><%# Convert.ToDateTime(Eval("EventDate")).ToShortTimeString()%></td>                

</tr>

</ItemTemplate>

</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.


Login to add your contents and source code to this article
 About the author
 
Scott Lysle
Freelance software developer residing in Alabama. Bachelors, Masters Degrees from Wichita State University. I spent the first half of my career working on aircraft controls and displays and in that time I worked on the cockpits for the OH-58 AHIP, the AH-1W, the V-22, the F-22, the C-130J, the C-5 AMP, AWACS, JPATS, and a few others. Since 1997 I have been largely involved with Windows and web development, GIS application development, consumer electronics development (embedded linux/java), but still sometimes work on aircraft and military projects, the most recent of which was the presidential transport helicopter. I tend to work primarily with C/C++, Java, VB, and C#.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
NerdDinner 1.0.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
Jquery by Prem On July 16, 2009
Table sorter using jquery
Reply | Email | Delete | Modify | 
Great Post by Lida On October 5, 2009
   thanks for this jquery codes...
Reply | Email | Delete | Modify | 
What about large record sets? by Rod On December 11, 2009
I am a bit worried when it comes to large data returns, like thousands of rows. This idea will fail on performance. It would be nice to make a call back pagination with sorting.
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.