Search code examples
javascriptjqueryasp.netajaxpagination

Server side paging with ajax & jQuery


Alright. So I have a table which holds a list of users.

<table id="UserTableContainer">
    <tr>
        <th>Firstname</th>
        <th>Lastname</th>
    </tr>
</table>

When I load the page I call a JSON method to retrieve the list of users from the server.

$(function () {
    $.getJSON(
        '/Account/UserList',
        null,
        function (data) {
            $.each(data, function (i, item) {
                PrintUsers(item);
            });
        });
});

Where my PrintUsers-method uses the jQuery template to add the users to each of its row in the table.

function PrintUsers(item) {
$.template('userList', '<tr>\
 <td>${Firstname}</td>\
 <td>${Lastname}</td>\
 </tr>');

$.tmpl('userList', item).appendTo("#UserTableContainer");

On the server side I get the list from an API.

public JsonResult UserList()
{
    try
    {
        List<User> users;         

        users = LoadUser(new UserFilter());
        }
        return Json(users, JsonRequestBehavior.AllowGet);
    }
    catch (Exception ex)
    {
        return Json(JsonRequestBehavior.DenyGet);
    }
}

The API which I am using to get the list already has built in functionality on paging. There's an overload option to pass int startIndex and int pageSize into the UserFilter() object.

What do I need to add in my jQuery and ajax calls to add paging functionality to my table? I'm lost at where I should begin.


Solution

  • Assuming you know how many pages there when the page is first generated you can create a list block for your paging list like -

    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        ...
    </ul>
    

    You could then change your jQuery to something like -

    function getPage(startPage, selectedPageSize) {
        $.getJSON(
            '/Account/UserList?startPage=' + startPage + '?pageSize=' + selectedPageSize,
            null,
            function (data) {
                $.each(data, function (i, item) {
                    PrintUsers(item);
                });
            }
        );
    }
    
    var pageSize = 10;
    $(document).ready(function() {
        getPage(0, pageSize);
    });
    
    $(function(){
        $('li').click(function() {
            var page = $(this).text();
            getPage(page, pageSize);
        });
    });