cs
public static string GeneratePagingHtml(int currentPage, int totalPages, string baseUrl)
{
StringBuilder sb = new StringBuilder();
sb.Append("<div class=\"pagination\">");
// 上一页
if (currentPage > 1)
{
sb.Append("<a href=\"" + baseUrl + "?page=" + (currentPage - 1) + "\">上一页</a>");
}
else
{
sb.Append("<span class=\"disabled\">上一页</span>");
}
// 页码
for (int i = 1; i <= totalPages; i++)
{
if (i == currentPage)
{
sb.Append("<span class=\"current\">" + i + "</span>");
}
else
{
sb.Append("<a href=\"" + baseUrl + "?page=" + i + "\">" + i + "</a>");
}
}
// 下一页
if (currentPage < totalPages)
{
sb.Append("<a href=\"" + baseUrl + "?page=" + (currentPage + 1) + "\">下一页</a>");
}
else
{
sb.Append("<span class=\"disabled\">下一页</span>");
}
sb.Append("</div>");
return sb.ToString();
}
这个函数接受三个参数:
currentPage
: 当前页码totalPages
: 总页数baseUrl
: 分页链接的基础 URL
函数会生成一个包含上一页、页码和下一页的 HTML 分页导航
使用示例:
cs
int currentPage = 3;
int totalPages = 10;
string baseUrl = "~/MyPage.aspx";
string paginationHtml = GeneratePagingHtml(currentPage, totalPages, baseUrl);
生成的 HTML 输出:
html
<div class="pagination">
<a href="~/MyPage.aspx?page=2">上一页</a>
<a href="~/MyPage.aspx?page=1">1</a>
<a href="~/MyPage.aspx?page=2">2</a>
<span class="current">3</span>
<a href="~/MyPage.aspx?page=4">4</a>
<a href="~/MyPage.aspx?page=5">5</a>
<a href="~/MyPage.aspx?page=4">下一页</a>
</div>