首页 > 解决方案 > 如何创建动态分页

问题描述

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

  <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 页(比如说)。我想在 Next 按钮中显示数字 1 到 5 的链接按钮。这样分页导航就会变成动态的。请帮助

标签: javascriptc#asp.net-mvc

解决方案


如果我理解正确,您担心的是您想限制生成的链接数量,以便用户看到的不是从 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.Min确保Math.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)没有补偿。这可能会得到改进,或者您可以保持原样。

该代码也可在fiddle中找到。


推荐阅读