简体   繁体   English

使用Ajax和jQuery进行服务器端分页

[英]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. 加载页面时,我调用JSON方法以从服务器检索用户列表。

$(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. 我的PrintUsers方法使用jQuery模板将用户添加到表中的每一行。

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. 在服务器端,我从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. 我用来获取列表的API已经在分页上具有内置功能。 There's an overload option to pass int startIndex and int pageSize into the UserFilter() object. 有一个重载选项可以将int startIndex和int pageSize传递给UserFilter()对象。

What do I need to add in my jQuery and ajax calls to add paging functionality to my table? 我需要在jQuery和ajax调用中添加什么才能向表中添加分页功能? I'm lost at where I should begin. 我迷失在应该开始的地方。

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 - 然后,您可以将jQuery更改为-

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM