如何在C# WebForms中实现带省略号的纯HTML分页
分页省略号动态显示逻辑优化方案
问题场景
当前分页实现固定展示前5页+末5页,但需要根据当前页码动态调整显示范围,比如:
page 1: 1 2 3... 48 49 50
page 2: 1 2 3 ... 48 49 50
page 3: 1... 3 4 5... 48 49 50
核心需求是根据当前页的位置,动态切换展示的页码组,避免固定范围导致的不符合预期的分页效果。
优化后的代码实现
public string CreatePagingLinks(int currentPage, int matches, string baseURL, int rowsPerPage) { StringBuilder pagingInfo = new StringBuilder(); // 用StringBuilder提升拼接效率 int maxpages = (matches + rowsPerPage - 1) / rowsPerPage; // 修正总页数计算,避免整除时少算一页 int visiblePages = 3; // 中间连续显示的页码数量,可按需调整 // 上一页按钮 if (currentPage == 1) { pagingInfo.Append("Prev | "); } else { pagingInfo.Append($"<a href=\"{baseURL}page={currentPage - 1}\">Prev</a> | "); } // 首页显示逻辑 if (currentPage > visiblePages + 1) { pagingInfo.Append($" <a href=\"{baseURL}page=1\">1</a> ... "); } else if (currentPage != 1) { pagingInfo.Append($" <a href=\"{baseURL}page=1\">1</a> "); } // 中间动态页码组 int startPage = Math.Max(2, currentPage - (visiblePages / 2)); int endPage = Math.Min(maxpages - 1, currentPage + (visiblePages / 2)); // 保证连续页码数量符合设置 if (endPage - startPage + 1 < visiblePages) { if (startPage == 2) { endPage = Math.Min(startPage + visiblePages - 1, maxpages - 1); } else if (endPage == maxpages - 1) { startPage = Math.Max(endPage - visiblePages + 1, 2); } } for (int k = startPage; k <= endPage; k++) { if (k == currentPage) { // 当前页高亮(示例用加粗) pagingInfo.Append($" <strong>{k}</strong> "); } else { pagingInfo.Append($" <a href=\"{baseURL}page={k}\">{k}</a> "); } } // 末页显示逻辑 if (currentPage < maxpages - visiblePages) { pagingInfo.Append($" ... <a href=\"{baseURL}page={maxpages}\">{maxpages}</a> "); } else if (currentPage != maxpages) { pagingInfo.Append($" <a href=\"{baseURL}page={maxpages}\">{maxpages}</a> "); } // 下一页按钮 if (currentPage == maxpages) { pagingInfo.Append(" | Next"); } else { pagingInfo.Append($" | <a href=\"{baseURL}page={currentPage + 1}\">Next</a>"); } return pagingInfo.ToString(); }
关键逻辑说明
- 总页数修正:用
(matches + rowsPerPage - 1) / rowsPerPage替代原计算方式,解决总记录数刚好整除每页条数时少算一页的问题。 - 首页展示规则:当当前页距离首页超过
visiblePages+1时,显示首页+省略号;否则直接展示首页。 - 中间动态页码:以当前页为中心,左右各扩展
visiblePages/2个页码,同时限制在首页和末页之间,保证连续页码数量稳定。 - 末页展示规则:当当前页距离末页超过
visiblePages时,显示省略号+末页;否则直接展示末页。 - 当前页高亮:给当前页添加加粗样式,提升用户识别效率。
效果验证
currentPage=1:Prev | 1 2 3 ... 50 | NextcurrentPage=3:Prev | 1 ... 2 3 4 ... 50 | NextcurrentPage=47:Prev | 1 ... 46 47 48 ... 50 | NextcurrentPage=50:Prev | 1 ... 48 49 50 | Next
内容的提问来源于stack exchange,提问作者rlatmfrl
相关产品推荐
相关产品推荐

