我正在尝试在我网站的最新新闻部分创建一些分页。我设法实际上让页面导航工作,以便每个页面都与下一个和上一个按钮一起输出到屏幕的底部,但是,当我们有一个页面时,我还想尝试减少分页字段的大小。整体上有大量的页面。考虑到这一点,我想尝试模仿以下行为:
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标准,但这不是我正在寻找的行为。
非常感谢任何帮助。
答案 0 :(得分:5)
稍作改动,您提到的规则变得更容易理解。
以下规则集是等效的:
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输出,您应该好好去:)
注意:我做了第4个选项(对于当前页面),因为您通常希望将其呈现为不可点击的项目。