Paging in ASP.NET using jTemplate, jQuery & JSON

Posted by: Aamir Hasan , on 11/23/2010, in Category jQuery and ASP.NET
Views: 168627
Abstract: This article demonstrates how to apply paging in jTemplate in ASP.NET using jQuery and JSON.

This article demonstrates how to apply paging in ASP.NET using jTemplate, jQuery and JSON. When working with a large dataset, it’s not a good idea to show all the records at once as it leads to performance issues in your website if a large number of visitors visit your site. Thus paging helps improve performance as the records are processed on demand.

Note: If you are not familiar with using jTemplate in ASP.NET, read my article
jTemplate, jQuery and JSON in ASP.NET before reading this one. Let’s start.

Step 1: Open VS 2010. Create a new ASP.NET project using File > Web Site. Give the website a name and press the OK button. In this website, I have created a Message and GridDataSet classes as shown below. 

public class Message
{
    public long ID { get; set; }
    public string Subject { get; set; }
    public String Body { get; set; }
    public DateTime Date { get; set; }
}
 
public class GridDataSet
{
    public int PageNumber { get; set; }
    public int TotalRecords { get; set; }
    public int PageSize { get; set; }
    public List<Message> MessageList { get; set; }
}

Step 2: I have created Messages() function which will return a list of Messages to the FetchData function. The FetchData function will return GridDataSet List.

using System.Web.Script.Serialization;

[WebMethod]
public static GridDataSet FetchData(int pageSize, int pageNumber)
{
    return new GridDataSet { PageNumber = pageNumber, TotalRecords = Messages().Count, PageSize = pageSize, MessageList = Messages().Skip(pageSize * pageNumber).Take(pageSize).ToList<Message>() };
}
 
public static List<Message> Messages()
{
    return new List<Message>()
    {
        new Message(){ ID=101, Subject="Aamir Hasan",Body="HI, How are you ",Date=DateTime.Now },
        new Message(){ ID=102, Subject="demo tutorial",Body="i have you visited",Date=DateTime.Now },
        new Message(){ ID=103, Subject="banner",Body="verfied",Date=DateTime.Now },
        new Message(){ ID=104, Subject="embed flash",Body="?",Date=DateTime.Now },
        new Message(){ ID=105, Subject="dotnetcurry.com",Body=".NET articles",Date=DateTime.Now },
        new Message(){ ID=106, Subject="Aamir Hasan",Body="done",Date=DateTime.Now },
        new Message(){ ID=107, Subject="asp.net",Body="asp.net..",Date=DateTime.Now },
        new Message(){ ID=108, Subject="Aamir Hasan 4",Body="...",Date=DateTime.Now },
        new Message(){ ID=109, Subject="Aamir Hasan 5",Body="...",Date=DateTime.Now },
        new Message(){ ID=1010, Subject="Aamir Hasan 6",Body="...",Date=DateTime.Now },
        new Message(){ ID=1011, Subject="Aamir Hasan 7",Body="...",Date=DateTime.Now },
        new Message(){ ID=1012, Subject="Aamir Hasan 8",Body="...",Date=DateTime.Now },
        new Message(){ ID=1013, Subject="Aamir Hasan 9",Body="...",Date=DateTime.Now }   
    };
}
 
Step 3: You can find the 'ForEachMessageTemplate.htm' file inside the jTemplate folder, which will used to render the html. I have also applied CSS on the table.

Step 4: Add the following code to Default.aspx page. On page load, the jQuery Ajax method will send the page size and page number to server side to retrieve the JSON Object.

 
<link href="Styles/Style.css" rel="stylesheet" type="text/css" />
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script src="http://github.com/malsup/corner/raw/master/jquery.corner.js?v2.09" type="text/javascript"></script>
<script src="Scripts/jtemplates.js" type="text/javascript"></script>
<script type="text/javascript">
 
    function Loader(isFade) {
        if (isFade) {
            $('#progressBackgroundFilter').fadeIn();
            $('#loadingbox').fadeIn();
            $('#Loader').fadeIn();
        } else {
            $('#progressBackgroundFilter').fadeOut();
            $('#loadingbox').fadeOut();
            $('#Loader').fadeOut();
        }
    }
 
    $(document).ready(function () {
        var pageSize = 5;
        var pageNumber = 0;
        getData(pageSize, pageNumber);
    });
    function getData(pageSize, pageNumber) {
        defaultParameters = "{pageSize:" + pageSize + ",pageNumber:" + pageNumber + "}";
        Loader(true);
        $.ajax({
            type: "POST",
            url: "Default.aspx/FetchData",
            data: defaultParameters,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: (function Success(data, status) {
                $('#placeholder').setTemplateURL('JTemplates/ForEachMessageTemplate.htm',
                                null, { filter_data: false });
                $('#placeholder').processTemplate(data.d)
                NoRecord(eval(data.d.MessageList));
                Loader(false);
                setPageNumber(pageSize);
            }),
            error: (function Error(request, status, error) {
                $("#placeholder").html(request.statusText).fadeIn(1000);
                Loader(false);
            })
        });
 
    }
    function NoRecord(e) {
        if (e == "")
        { $('#nofound').show(); }
        else
        { $('#nofound').hide(); }
    }
    function setPageNumber(pageSize) {
        $("#ddPaging").change(function (e) {
            var pageIndex = $(this).val() - 1;
            if (pageIndex != -1)
                getData(pageSize, pageIndex);
 
        });
    }
</script>
 
 
You can see there are div elements as shown below to display records and also a loader which will be run before loading records and unload after retrieving records.

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <h1>How to Apply Paging in Jtemplate in asp.net using,Linq</h1>
    <p><div id="placeholder" style="clear: both;"></div></p>
    <div id="Loader">
        <div id="loadingbox">
            <br/><br/><br/>
            processing</div>
        <div id="progressBackgroundFilter"></div>
    </div>
</asp:Content>

After running the code, the following output will be created.

Output 

jTemplate Paging

I have used firebug to comfim that only 5 records has been retrieved by jQuery Ajax method to the client side, as shown below. 

Firebug Jtemplate

Conclusion

Using paging in ASP.NET with jTemplate, jQuery and JSON makes your site perform better and faster, especially in situations when your site has a large number of visitors.

The entire source code of this article can be downloaded over
here

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Aamir Hasan is a Sr. Software Engineer and Technical Lead in a US based firm, having five years of experiences working in Software Design, Web Development, Consultancy and Training, using SQL Server and .NET Framework. He is an SEO professional too. He is capable of coordinating off-shore high level web development projects. Aamir also blogs at www.aspxtutorial.com and www.dotnetplace.com


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by john on Tuesday, November 23, 2010 6:45 AM
Excellent work.I like it
Comment posted by H. McCreight on Tuesday, November 23, 2010 2:38 PM
This is nothing new and can be done with ASP.NET , VB.NET,C# and SQL Server
Comment posted by Ahmed Al-BaGaLaTy on Monday, December 20, 2010 6:28 AM
if there is an html tags on body field for example the text will not display
how to display HTML Field in this case ??
Comment posted by tomato boy on Tuesday, January 4, 2011 4:34 AM
Excellent article.
Comment posted by zeeshan on Tuesday, January 18, 2011 5:38 AM
wah sir gr8 tutorial good
Comment posted by codeben on Sunday, December 4, 2011 9:53 PM
jtemplate has been discontinued.
Instead how do you implement this using jsrender?
Comment posted by gjhg on Wednesday, January 11, 2012 1:22 AM
jhfgjfjf
Comment posted by John on Sunday, January 22, 2012 3:37 AM
Excellent, i like your logic.
Comment posted by Thomas on Tuesday, January 31, 2012 4:29 AM
jTemplates has NOT been discontinued, it is at 0.8 and author told me he will release 0.8.1 soon.
The discontinued luibrary is jquere template which is another thing
Comment posted by Hùng on Tuesday, October 30, 2012 10:35 PM
How to display Paging : << < 1 2 3 4 5 > >> ???
Comment posted by guru on Thursday, September 12, 2013 8:56 AM
Thank you for your Post
Comment posted by guru on Thursday, September 12, 2013 9:00 AM
i visit your Post in
http://dotnetplace.com/post/Fill-ASPNETDropdownlist-through-JSON-data-using-jQuery.aspx
for
Fill ASP.NETDropdownlist through JSON data using jQuery

i done what you did but my code directly go to error ( failed to load data)

below its my code

   <script src="Scripts/jquery-1.4.1.js"type="text/javascript"></script>
       <script type="text/javascript" language="javascript">
           $.ajax({
               type: "POST",
               url: "Default.aspx/fetchData",
               data: "{}",
               contentType: "application/json; charset=utf-8",
               dataType: "json",
               success: function (response) {
                   var Dropdown = $('#<%=DropDownList1.ClientID %>');
                   Dropdown.append(new Option("SELECT", 0));
                   $.each(response.d, function (index, item) {
                       Dropdown.append(new Option(item.Fullname, item.ID));
                   });
               },
               error: function () {
                   alert("Failed to load data");
               }
           });

           $(document).ready(function () {
               var dropdown = $('#<%=DropDownList1.ClientID %>');
               dropdown.change(function () {
                   $("#<%=msg.ClientID%>").text(dropdown.val());
               });
           });    
      
   </script>
</head>
<body>
    <form id="form1" runat="server">
    <h2>Fill Dropdown list using jQuery,JSON object</h2>
    <p><asp:DropDownList ID="DropDownList1" runat="server"/></p>
   <asp:Label ID="msg" runat="server"></asp:Label>
    </form>
</body>

Webservice code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;

namespace SimpleWebService
{

    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [System.Web.Script.Services.ScriptService]
    public class Service1 : System.Web.Services.WebService
    {

       [WebMethod]
        public static List<Employee> fetchData()
        {
            return new List<Employee>()      
                {
                    new Employee{ Fullname="Aamir Hasan", ID=1},
                    new Employee{ Fullname="Awais Ahmed", ID=2},
                    new Employee{ Fullname="Mahwish Khan", ID=3},
                    new Employee{ Fullname="Saba Khan", ID=4},
                    new Employee{ Fullname="Hina Ahmed", ID=5},
                    new Employee{ Fullname="Gill Gate", ID=6}
                };
         }
       }
               public class Employee
                      {
                            public string Fullname { get; set; }
                            public int ID { get; set; }
                         }

    }