分頁類
using System.Text;
using System.Web.Routing;
namespace System.Web.Mvc
{
public static class PagerHelper
{
/// <summary>
/// 擷取分頁
/// </summary>
/// <param name="urlFormat">url格式,用{0}代替頁碼</param>
/// <param name="pageIndex">當前頁</param>
/// <param name="pageSize">總頁數</param>
/// <param name="recordCount">總記錄數</param>
/// <param name="mode">分頁模式</param>
/// <returns>html</returns>
public static string Pager(this HtmlHelper helper, string urlFormat, int pageIndex, int pageSize, int recordCount, PageMode mode)
{
urlFormat = urlFormat.Replace("%7B0%7D", "{0}");
int pageCount = (recordCount % pageSize == 0 ? recordCount / pageSize : recordCount / pageSize + 1);
StringBuilder sb = new StringBuilder();
sb.AppendFormat("總共{0}條記錄,共{1}頁,當前第{2}頁 ", recordCount, pageCount, pageIndex);
if (pageIndex == 1)
sb.Append("首頁 ");
else
{
string url1 = string.Format(urlFormat.ToString(), 1);
sb.AppendFormat("<a href={0}>首頁</a> ", url1);
}
if (pageIndex > 1)
{
string url1 = string.Format(urlFormat.ToString(), pageIndex - 1);
sb.AppendFormat("<a href={0}>上一頁</a> ", url1);
}
else
sb.Append("上一頁 ");
if (mode == PageMode.Numeric)
sb.Append(GetNumericPage(urlFormat.ToString(), pageIndex, pageSize, recordCount, pageCount));
if (pageIndex < pageCount)
{
string url1 = string.Format(urlFormat.ToString(), pageIndex + 1);
sb.AppendFormat("<a href={0}>下一頁</a> ", url1);
}
else
sb.Append("下一頁 ");
if (pageIndex == pageCount)
sb.Append("末頁");
else
{
string url1 = string.Format(urlFormat.ToString(), pageCount);
sb.AppendFormat("<a href={0}>末頁</a>", url1);
}
return sb.ToString();
}
/// <summary>
/// 擷取數字分頁
/// </summary>
private static string GetNumericPage(string url, int pageIndex, int pageSize, int recordCount, int pageCount)
{
int k = pageIndex / 10;
int m = pageIndex % 10;
StringBuilder sb = new StringBuilder();
if (pageIndex / 10 == pageCount / 10)
{
if (m == 0)
{
k--;
m = 10;
}
else
m = pageCount % 10;
}
else
m = 10;
for (int i = k * 10 + 1; i <= k * 10 + m; i++)
{
if (i == pageIndex)
sb.AppendFormat("<span style=\"color: red\">{0}</span> ", i);
else
{
string url1 = string.Format(url.ToString(), i);
sb.AppendFormat("<a href={0}>{1}</a> ", url1, i);
}
}
return sb.ToString();
}
}
/// <summary>
/// 分頁模式
/// </summary>
public enum PageMode
{
/// <summary>
/// 普通分頁模式
/// </summary>
Normal,
/// <summary>
/// 普通分頁加數字分頁
/// </summary>
Numeric
}
}
<%= Html.Pager(Url.Action("Main",new {page="{0}"}),10,10,1000, PageMode.Numeric) %>
以{0}代替頁索引的參數即可,使用非常方便.