在ABP框架开发中,分页功能是处理大量数据展示的基础能力,能够避免一次性加载过多数据导致的性能问题,同时提升用户的使用体验。实现分页功能需要服务端和前端配合完成,服务端负责接收分页参数并处理数据查询,前端负责传递分页参数并展示分页后的结果。

分页功能的核心参数
实现分页功能首先需要明确两个核心参数:页码和每页条数。页码表示当前请求的页数,从1开始计数;每页条数表示每一页展示的数据数量。基于这两个参数,我们可以计算出数据查询时的跳过数量和获取数量:跳过数量 = (页码 - 1) * 每页条数,获取数量 = 每页条数。
服务端分页实现
定义分页请求DTO
首先在应用层定义分页请求的数据传输对象,用于接收前端传递的分页参数:
// 分页请求DTO
public class GetPagedProductsInput
{
// 页码,默认第1页
public int PageIndex { get; set; } = 1;
// 每页条数,默认每页10条
public int PageSize { get; set; } = 10;
}应用服务中实现分页逻辑
在应用服务中接收分页参数,结合仓储完成分页查询,同时返回总数据量用于前端计算总页数:
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Abp.Application.Services;
using Abp.Application.Services.Dto;
namespace MyProject.Application.Products
{
public class ProductAppService : ApplicationService, IProductAppService
{
private readonly IRepository<Product, int> _productRepository;
public ProductAppService(IRepository<Product, int> productRepository)
{
_productRepository = productRepository;
}
public async Task<PagedResultDto<ProductDto>> GetPagedProductsAsync(GetPagedProductsInput input)
{
// 计算跳过的记录数
var skipCount = (input.PageIndex - 1) * input.PageSize;
// 查询总数据量
var totalCount = await _productRepository.CountAsync();
// 分页查询数据
var products = await _productRepository.GetAll()
.OrderBy(p => p.Id)
.Skip(skipCount)
.Take(input.PageSize)
.ToListAsync();
// 转换为DTO
var productDtos = ObjectMapper.Map<List<ProductDto>>(products);
// 返回分页结果
return new PagedResultDto<ProductDto>(totalCount, productDtos);
}
}
}定义分页结果DTO
ABP内置了PagedResultDto类型,已经包含了总数据量和当前页数据两个属性,直接使用即可,无需重复定义。
前端调用分页接口
前端调用分页接口时,只需要传递对应的页码和每页条数参数,然后处理返回的分页结果即可。以下是使用jQuery调用接口的示例:
// 分页查询产品数据
function getProducts(pageIndex, pageSize) {
$.ajax({
url: '/api/services/app/Product/GetPagedProductsAsync',
type: 'post',
contentType: 'application/json',
data: JSON.stringify({
PageIndex: pageIndex,
PageSize: pageSize
}),
success: function (res) {
// res.result.totalCount 是总数据量
// res.result.items 是当前页的产品数据列表
renderProducts(res.result.items);
renderPagination(res.result.totalCount, pageIndex, pageSize);
}
});
}
// 渲染产品列表
function renderProducts(products) {
var html = '';
products.forEach(function (item) {
html += '<div>' + item.name + '</div>';
});
$('#productList').html(html);
}
// 渲染分页控件
function renderPagination(totalCount, currentPage, pageSize) {
var totalPages = Math.ceil(totalCount / pageSize);
var paginationHtml = '';
for (var i = 1; i <= totalPages; i++) {
if (i === currentPage) {
paginationHtml += '<span class="current-page">' + i + '</span>';
} else {
paginationHtml += '<a href="javascript:;" onclick="getProducts(' + i + ',' + pageSize + ')">' + i + '</a>';
}
}
$('#pagination').html(paginationHtml);
}
// 初始加载第一页,每页10条
getProducts(1, 10);注意事项
- 分页查询时一定要添加排序条件,否则每次查询的结果顺序可能不一致,导致分页数据重复或遗漏。
- 如果数据量非常大,CountAsync查询可能会比较耗时,可以根据实际场景考虑是否缓存总数据量,或者采用其他优化方案。
- 前端传递的分页参数需要做合法性校验,比如页码不能小于1,每页条数不能超过最大限制,避免无效查询。
ABP分页功能ASP.NET_Core修改时间:2026-06-04 14:59:03