C#实现分页组件

时间:2023-03-09 08:05:22
C#实现分页组件

分页无论是前端和后端,基本都有广泛应用!下面通过一个小小案例完成这个分页效果:

参数含义:string urlFormat: 要传给服务器端的URL地址格式,方便在点超链接时进行相应的跳转

long totalSize:     总的数据条数。

long pageSize:    每页多少条数据

long currentPage: 当前的页数

后面通过具体的一个案例来用这个分页方法:

一.分页方法:

       /// <summary>
/// 生成页码的html
/// </summary>
/// <param name="urlFormat">超链接的格式。list.ashx?pagenum={pageNum}。地址中用{pagenum}做为当前页码的占位符</param></param>
/// <param name="totalSize">总数据条数</param>
/// <param name="pageSize">每页多少条数据</param>
/// <param name="currentPage">当前页</param>
/// <returns></returns>
public static RawString Pager(string urlFormat, long totalSize,
long pageSize, long currentPage)
{
StringBuilder sb = new StringBuilder();
//总页数
long totalPageCount = (long)Math.Ceiling((totalSize * 1.0f) / (pageSize * 1.0f));
//当前页的前几页
long firstPage = Math.Max(currentPage - , );
//当前页的后几页
long lastPage = Math.Min(currentPage + , totalPageCount);
//绘制分页,首页
sb.AppendLine("<div><a href='" + urlFormat.Replace("{pageNum}", "") + "'>首页</a>");
//绘制分页中间数据部分
for (long i = firstPage; i < lastPage; i++)
{
string url = urlFormat.Replace("{pageNum}", i.ToString());
if (i == currentPage) //点击后就不显示超链接
{
sb.AppendLine("<a>" + i + "</a>");
}
else
{
sb.AppendLine("<a href='" + url + "'>" + i + "</a>");
}
}
//显示最后一页
sb.AppendLine("<a href='" + urlFormat.Replace("{pageNum}", totalPageCount.ToString()) + "'>末页</a></div>");
return new RawString(sb.ToString());
}

二.案例调用:

服务器端(test.ashx):这里为了方便看到效果,展示数据直接用的固定数据

 public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/html";
long pn = Convert.ToInt64(context.Request["pn"]);
if (pn == ) //Convert.ToInt64(null)返回的是0
{
pn = ;
}
long[] num = new long[]; //这里的数据用的是固定数据
for (int i = ; i < ; i++)
{
num[i] = ((pn-) * ) + i;
}
OutputRazor(context, "~/test.cshtml", new { nums=num,page=pn}); //这里用的Razor模板引擎
}

这里的Razor方法见:http://www.cnblogs.com/fengxuehuanlin/p/5313354.html

UI端展示(test.cshtml):

<body>
<ul>
@{
foreach (int i in Model.nums)
{
<li>@i</li>
}
}
</ul>
@Pager("test.ashx?pn={pageNum}", 1020, 50, Model.page);
</body>

效果图:

C#实现分页组件

三.jQuery分页插件:

前面写的这些主要是进行功能的实现,样式效果差了点。下面贴上通过jQuery实现的分页效果

jQuery的效果图,及调用方法:

C#实现分页组件

文件下载地址:http://pan.baidu.com/s/1cofez0