gpt4 book ai didi

c# - 分页逻辑 : Inserting . .. 当有很多页面时而不是中间页面

转载 作者:太空宇宙 更新时间:2023-11-03 20:06:20 25 4
gpt4 key购买 nike

我正在尝试在我网站的最新新闻部分创建一些分页。我已经设法使页面导航正常工作,以便在屏幕底部输出每个页面以及下一个和上一个按钮,但是,我也想尝试在我们有大量页面时减小分页字段的大小整体页面。考虑到这一点,我想尝试模仿以下行为:

When the total number of pages is less than 7, output the pagination as:

<Previous> 1 2 3 4 5 6 7 <Next>

However, if the total number of pages is not less than 7, output only the first 2
pages, the last 2 pages and the 2 pages either side of the current page as well
as the link for the current page. In place of the missing page, there should be
a single ...

我已经使用以下代码设法实现了这种行为:

@if (totalPages > 1){
<ul class="pager">
@if (page > 1){
<li><a href="?page=@(page-1)">Previous</a></li>
}
@for (int p = 1; p < totalPages + 1; p++){
var linkClass = (p == page) ? "disabled" : "active";
if ((p >= page - 2 && p <= page + 2 || p <= 2 || p >= totalPages -2)
|| totalPages <= 7){
<li class="@Html.Raw(linkClass)">
<a href="?page=@p">@p</a>
</li>
}
}

@if (page < totalPages){
<li><a href="?page=@(page+1)">Next</a></li>
}
</ul>
}

但是,我现在纠结的主要部分是如何输出单个 ... 来代替不符合条件的页面。我可以轻松地输出多个 ... 在 if 条件下使用 else 条件,但这不是我要寻找的行为。

如有任何帮助,我们将不胜感激。

最佳答案

稍微改写一下,您提到的规则就更容易理解了。

以下规则集是等效的:

Any page number that is either the 
first,
second,
second before current,
first before current,
current,
first after current,
second after current,
second to last,
or last page
should be displayed. Any other page should be an ellipsis.

用代码计算,这就变成了:

//Note: I'm addressing the pages as a 1-based index. 
//If 0-based is needed, just add -1 to all index values

bool previousPageIsEllipsis = false;

for(int i = 1; i <= totalpages; i++)
{
if(i == currentpage) {
//Print current page number

previousPageIsEllipsis = false;
}
else
{
if( i == 1
|| i == 2
|| i == currentpage - 2
|| i == currentpage - 1
|| i == currentpage + 1
|| i == currentpage + 2
|| i == totalpages - 1
|| i == totalpages)
{
//Print a visible link button

previousPageIsEllipsis = false;
}
else
{
if(previousPageIsEllipsis)
{
//an ellipsis was already added. Do not add it again. Do nothing.
continue;
}
else
{
//Print an ellipsis
previousPageIsEllipsis = true;
}
}
}
}

我没有添加实际的代码,因为你已经有了。但在这里,您会看到三个选项:显示页面、显示省略号,或者如果前一个元素已经是省略号则不显示任何新内容。

只需在 //comment lines 中插入所需的 HTML 输出,您就可以开始了:)

注意:我做了第四个选项(针对当前页面),因为您通常希望将其呈现为不可点击的项目。

关于c# - 分页逻辑 : Inserting . .. 当有很多页面时而不是中间页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23243201/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com