功能需求
- 支援「上一頁、下一頁」、「首頁、末頁」。
- 當前頁碼高亮顯示。
- 頁碼過多時自動省略(顯示當前頁前後 N 頁)。
- 可自訂每頁筆數、總筆數、目前頁碼、前後顯示範圍。
完整實作碼
public string PageLink(int pageSize, int recordCount, int currentPage, int prev, int next) {
// 總頁數
int pageCount = (int)Math.Ceiling((double)recordCount / pageSize);
if (pageCount <= 1) return string.Empty;
StringBuilder sb = new StringBuilder();
// 上一頁
if (currentPage > 1) {
sb.Append($"<a href=\"?page={currentPage - 1}\">上一頁</a> ");
}
// 首頁與省略號
if (currentPage > prev + 1) {
sb.Append("<a href=\"?page=1\">1</a> ... ");
}
// 動態調整前後顯示範圍,確保總顯示頁數不變
if (currentPage < prev) next += prev - currentPage + 1;
if (next > pageCount - currentPage) prev += next - (pageCount - currentPage);
// 頁碼迴圈
for (int i = 1; i <= pageCount; i++) {
if (i == currentPage) {
sb.Append($"<a href=\"?page={i}\" class=\"current\"><font color=\"red\">{i}</font></a> ");
}
else if (i > currentPage - prev - 1 && i < currentPage + next + 1) {
sb.Append($"<a href=\"?page={i}\">{i}</a> ");
}
}
// 末頁與省略號
if (currentPage < pageCount - next) {
sb.Append($"... <a href=\"?page={pageCount}\">{pageCount}</a>");
}
// 下一頁
if (currentPage < pageCount) {
sb.Append($" <a href=\"?page={currentPage + 1}\">下一頁</a>");
}
return sb.ToString();
}
參數說明
| 參數 | 型別 | 說明 |
| pageSize | int | 每頁筆數 |
| recordCount | int | 總筆數 |
| currentPage | int | 目前頁碼(1-based) |
| prev | int | 當前頁前方顯示頁數 |
| next | int | 當前頁後方顯示頁數 |
使用範例
<%-- 頁面上 --%>
<div class="pager">
<%= PageLink(10, totalRecords, currentPage, 3, 3) %>
</div>
<%-- Code-behind --%>
int pageSize = 10;
int currentPage = Request.QueryString["page"] != null ? int.Parse(Request["page"]) : 1;
int totalRecords = GetTotalCount(); // 自行實作
string pagerHtml = PageLink(pageSize, totalRecords, currentPage, 3, 3);
litPager.Text = pagerHtml; // 用 Literal 輸出 HTML
CSS 樣式建議
.pager a { margin: 0 3px; text-decoration: none; color: #333; }
.pager a.current { font-weight: bold; color: red; }
.pager a:hover { text-decoration: underline; }
擴充建議
- URL 重寫:將
?page=N 改為 /page/N,配合 ASP.NET Routing 或 URL Rewrite。
- Ajax 分頁:連結加
data-ajax="true",前端攔截 click 事件局部更新。
- 泛型化:將連結格式、CSS 類別參數化,支援 Bootstrap、Tailwind 等框架。
- 無障礙:加入
aria-label、rel="prev/next" 提升 SEO 與可存取性。
常見坑點
currentPage 需驗證範圍(1 ~ pageCount),避免負數或超出總頁數。
recordCount = 0 時直接回傳空字串,避免除零錯誤。
- 查詢字串若包含其他參數(如搜尋關鍵字),需保留並附加
page 參數。