如何创建动态分页



我已经在 MVC 中完成了服务器端分页,但我无法动态显示数字以及下一个和上一个链接按钮。请给我一些想法。

<nav aria-label="Page navigation example">
<ul class="pagination">
@for (int i = 1; i <= Model.PageCount; i++) // PageCount is Number of total Pages
{
<li class="page-item">
@if (i != Model.CurrentPageIndex) //Current Page say 1..2...3..etc
{
<a class="page-link" href="javascript:;" onclick="myClick(@i)">@i</a>
}
else
{
<span>@i</span>
}
</li>
}
</ul>
</nav>

我的问题是如果我总共有 10 页(比如说)。我想显示数字 1 到 5 的链接按钮 下一步 按钮 .使分页导航变得动态,请帮助

如果我理解正确,您担心的是您希望限制生成的链接数量,以便而不是指向每个页面的链接,从 1 开始到PageCount结束,用户只能看到完整链接列表的范围。

这里的想法是引入另一个参数,称为numbersToShow,它表示要呈现的链接总数。

例如,当有 10 个页面时,链接总数可能为 5。

计算此子集的起始和结束索引的示例函数可能如下所示:

static (int min, int max) GetPagingRange( int currentPage, int totalPages, int numbersToShow = 5 )
{
if ( currentPage < 1 || totalPages < 1 || currentPage > totalPages ) throw new ArgumentException();
if ( numbersToShow < 1 ) throw new ArgumentException();
var min = Math.Max(1, currentPage - numbersToShow/2);
var max = Math.Min(totalPages, currentPage + numbersToShow/2 + Math.Max( 0, min - currentPage + numbersToShow/2 ) );
return (min, max);
}

这里发生的事情是,我们从当前页面开始,并尝试将其设置为动态范围的中间(因此我们将numbersToShow/2带到左侧和右侧)。Math.MinMath.Max都确保我们保持在有效范围内。

在计算max时,还有另一个组件试图在呈现前几页时补偿范围左侧部分的缺失。

请考虑以下示例用法,该用法显示了返回的范围值:

Console.WriteLine( "Total pages:    10" );
Console.WriteLine( "Numers to show: 5" );
int totalPages = 10;
for ( int currentPage = 1; currentPage <= totalPages; currentPage++ )                 
{
var result = GetPagingRange( currentPage, totalPages );
Console.WriteLine( $"CurrentPage: {currentPage}, starting page index: {result.min} ending page index: {result.max}");
}   

这里的输出是

Total pages:    10
Numers to show: 5
CurrentPage: 1, starting page index: 1 ending page index: 5
CurrentPage: 2, starting page index: 1 ending page index: 5
CurrentPage: 3, starting page index: 1 ending page index: 5
CurrentPage: 4, starting page index: 2 ending page index: 6
CurrentPage: 5, starting page index: 3 ending page index: 7
CurrentPage: 6, starting page index: 4 ending page index: 8
CurrentPage: 7, starting page index: 5 ending page index: 9
CurrentPage: 8, starting page index: 6 ending page index: 10
CurrentPage: 9, starting page index: 7 ending page index: 10
CurrentPage: 10, starting page index: 8 ending page index: 10

请注意,尽管补偿适用于起始页(例如,当当前页面为 1 时,范围为 1 到 5),但当呈现的最后几页时(例如,在最后 10 页上,范围为 8 到 10),则没有补偿)。这可能会得到改进,或者您可以保持原样。

该代码也可以在小提琴中找到。

最新更新