MVC3之分页
环境:VS2010+Sql2008+NHiberNate
第一步: 建立PageList类,代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Redboil.Bss.Web.Apps
{
public class PageList<T> : List<T>
{
/// <summary>
/// 当前分页
/// </summary>
public int PageIndex { get; private set; }
/// <summary>
/// 显示数据条目
/// </summary>
public int PageSize { get; private set; }
/// <summary>
/// 总页数
/// </summary>
public int TotalCount { get; private set; }
public PageList(IEnumerable<T> source, int pageIndex, int pageSize, int totalCount)
{
PageIndex = pageIndex;
PageSize = pageSize;
TotalCount = totalCount;
AddRange(source);
}
}
}
第二步:建立PageHelper,代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Redboil.Bss.Web.Apps
{
public static class PagerHelper
{
private const int defaultDisplayCount = 11;
public static readonly int PageSize = 10;
#region HtmlHelper Extensions
/// <summary>
/// Pager Helper Extensions
/// </summary>
/// <param name="htmlHelper"></param>
/// <param name="currentPage">当前页码</param>
/// <param name="pageSize">页面显示的数据条目</param>
/// <param name="totalCount">总记录数</param>
/// <param name="toDisplayCount">Helper要显示的页数</param>
/// <returns></returns>
public static string Pager(this HtmlHelper htmlHelper, int currentPage, int pageSize, int totalCount, int toDisplayCount)
{
RenderPager pager = new RenderPager(htmlHelper.ViewContext, currentPage, pageSize, totalCount, toDisplayCount);
return pager.RenderHtml();
}
/// <summary>
/// Pager Helper Extensions
/// </summary>
/// <param name="htmlHelper"></param>
/// <param name="currentPage">当前页码</param>
/// <param name="pageSize">页面显示的数据条目</param>
/// <param name="totalCount">总记录数</param>
/// <returns></returns>
public static string Pager(this HtmlHelper htmlHelper, int currentPage, int pageSize, int totalCount)
{
RenderPager pager = new RenderPager(htmlHelper.ViewContext, currentPage, pageSize, totalCount, defaultDisplayCount);
string pagerString = pager.RenderHtml();
return pagerString;
}
/// <summary>
/// IEnumerable extensions
/// </summary>
public static PageList<T> ToPageList<T>(this IEnumerable<T> source, int pageIndex, int pageSize, int totalCount)
{
return new PageList<T>(source, pageIndex, pageSize, totalCount);
}
#endregion
}
}
第三步,建立RenderPager类,实现分布呈现功能,代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text.RegularExpressions;
using System.Web.Mvc;
using System.Text;
namespace Redboil.Bss.Web.Apps
{
public class RenderPager
{
#region 字段
/// <summary>
/// 当前页面的ViewContext
/// </summary>
private ViewContext viewContext;
/// <summary>
/// 当前页码
/// </summary>
private readonly int currentPage;
/// <summary>
/// 页面要显示的数据条数
/// </summary>
private readonly int pageSize;
/// <summary>
/// 总的记录数
/// </summary>
private readonly int totalCount;
/// <summary>
/// Pager Helper 要显示的页数
/// </summary>
private readonly int toDisplayCount;
private readonly string pagelink;
#endregion
#region 构造函数
public RenderPager(ViewContext viewContext, int currentPage, int pageSize, int totalCount, int toDisplayCount)
{
this.viewContext = viewContext;
this.currentPage = currentPage;
this.pageSize = pageSize;
this.totalCount = totalCount;
this.toDisplayCount = toDisplayCount;
string reqUrl = viewContext.RequestContext.HttpContext.Request.RawUrl;
string link = "";
Regex re = new Regex(@"pageIndex=(\d+)|pageIndex=", RegexOptions.IgnoreCase);
MatchCollection results = re.Matches(reqUrl);
if (results.Count > 0)
{
link = reqUrl.Replace(results[0].ToString(), "pageIndex=[%page%]");
}
else if (reqUrl.IndexOf("?") < 0)
{
link = reqUrl + "?pageIndex=[%page%]";
}
else
{
link = reqUrl + "&pageIndex=[%page%]";
}
this.pagelink = link;
}
#endregion
#region 方法
public string RenderHtml()
{
if (totalCount <= pageSize)
return string.Empty;
//总页数
int pageCount = (int)Math.Ceiling(this.totalCount / (double)this.pageSize);
//起始页
int start = 1;
//结束页
int end = toDisplayCount;
if (pageCount < toDisplayCount) end = pageCount;
//中间值
int centerNumber = toDisplayCount / 2;
if (pageCount > toDisplayCount)
{
//显示的第一位
int topNumber = currentPage - centerNumber;
if (topNumber > 1)
{
start = topNumber;
}
if (topNumber > pageCount - toDisplayCount)
{
start = pageCount - toDisplayCount + 1;
}
//显示的最后一位
int endNumber = currentPage + centerNumber;
if (currentPage >= pageCount - centerNumber)
{
end = pageCount;
}
else
{
if (endNumber > toDisplayCount)
{
end = endNumber;
}
}
}
StringBuilder sb = new StringBuilder();
//Previous
if (this.currentPage > 1)
{
sb.Append(GeneratePageLink("<前一页", this.currentPage - 1));
}
if (start > 1)
{
sb.Append(GeneratePageLink("1", 1));
sb.Append("...");
}
//end Previous
for (int i = start; i <= end; i++)
{
if (i == this.currentPage)
{
sb.AppendFormat("<span class=\"current\">{0}</span>", i);
}
else
{
sb.Append(GeneratePageLink(i.ToString(), i));
}
}
//Next
if (end < pageCount)
{
sb.Append("...");
sb.Append(GeneratePageLink(pageCount.ToString(), pageCount));
}
if (this.currentPage < pageCount)
{
sb.Append(GeneratePageLink("后一页>", this.currentPage + 1));
}
//end Next
sb.Append(" <span><input type=\"text\" class=\"pagerInput\" id=\"pagerInput\" maxlength=\"4\" onkeypress=\"return event.keyCode>=48&&event.keyCode<=57\"/></span> ");
sb.Append(" <span><input type=\"button\" value=\"跳转\" class=\"btn3\" onclick=\"if (!isNaN(parseInt(pagerInput.value))) window.location='" + this.pagelink.Replace("[%page%]", "") + "'+pagerInput.value;\"/></span>");
return sb.ToString();
}
/// <summary>
/// 生成Page的链接
/// </summary>
/// <param name="linkText">文字</param>
/// <param name="PageNumber">页码</param>
/// <returns></returns>
private string GeneratePageLink(string linkText, int PageNumber)
{
string linkFormat = string.Format(" <a href=\"{0}\">{1}</a> ", this.pagelink.Replace("[%page%]", PageNumber.ToString()), linkText);
return linkFormat;
}
#endregion
}
}
第四步,Controller,
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Redboil.Bss.Model;
using Redboil.Bss.Web.Models.Redboil.Bss;
using Redboil.Bss.Web.Apps;
using Redboil.Bss.Core;
using Redboil.Bss.Service;
using NHibernate.Criterion;
namespace Redboil.Bss.Web.Controllers
{
public class EmployeeController : Controller
{
private WebContext db = new WebContext();
//
// GET: /Employee/
public ViewResult Index(int pageIndex = 1, string employeeName = "",string cellPhone = "")
{
int count = 0;
IList<Employee> list = Container.Instance.Resolve<IEmployeeService>().GetPaged(GetCondition(employeeName,cellPhone), pageIndex, PagerHelper.PageSize, "ID", false, out count);
PageList<Employee> pageList = list.ToPageList<Employee>(pageIndex, PagerHelper.PageSize, count);
return View(pageList);
}
private IList<ICriterion> GetCondition(string employeeName = "",string cellPhone = "")
{
Employee employee = new Employee();
List<ICriterion> queryConditions = new List<ICriterion>();
if (!string.IsNullOrEmpty(employeeName))
{
queryConditions.Add(new LikeExpression("Name", employeeName));
}
if (!string.IsNullOrEmpty(cellPhone))
{
queryConditions.Add(new LikeExpression("CellPhone", cellPhone));
}
return queryConditions;
}
}
第五步,视图页面(红色部分是关键代码),代码如下:
@using Redboil.Bss.Web.Apps
@model PageList<Redboil.Bss.Model.Employee>
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<link href="@Url.Content("~/Content/Styles/ViewPage.css")" rel="stylesheet" type="text/css" />
<table border="0" cellpadding="0" cellspacing="0" style="width: 100%; background-color: White;"
align="center">
<tr>
<td class="mbg">
<table cellspacing="0" cellpadding="0" width="100%" border="0" valign="top">
<tr>
<td>
<table style="height: 23px;" cellspacing="0" cellpadding="0" width="120" background="@Url.Content("~/Content/Images/m_17.gif")"
border="0">
<tr>
<td>
<span class="contentPageTitle"> >> 员工列表</span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td align="right" class="titleContentDivider" height="6">
</td>
</tr>
</table>
</td>
</tr>
</table>
<p>
@Html.ActionLink("创建新员工", "Create")
</p>
@using (Html.BeginForm())
{
<p>
姓名: @Html.TextBox("employeeName")
电话: @Html.TextBox("cellPhone")
<input type="submit" value="查询" class="btn3" /></p>
}
<table cellpadding="0" cellspacing="0" class="dataGrid">
<tr>
<th style="width: 100px;">
姓名
</th>
<th style="width: 100px;">
员工号
</th>
<th style="width: 100px;">
联系电话
</th>
<th style="width: 100px;">
身份证号码
</th>
<th style="width: 100px;">
出生日期
</th>
<th style="width: 100px;">
系统用户
</th>
<th style="width: 100px;">
家庭地址
</th>
<th style="width: 200px;">
操作
</th>
</tr>
@if (Model.Count > 0)
{
foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Number)
</td>
<td>
@Html.DisplayFor(modelItem => item.CellPhone)
</td>
<td>
@Html.DisplayFor(modelItem => item.Identification)
</td>
<td>
@item.Brithday.ToShortDateString()
</td>
<td>
@Html.DisplayFor(modelItem => item.IsUser)
</td>
<td>
@Html.DisplayFor(modelItem => item.Address)
</td>
<td>
@Html.ActionLink("修改", "Edit", new { id = item.ID }) |
@Html.ActionLink("详细信息", "Details", new { id = item.ID }) |
@Html.ActionLink("删除", "Delete", new { id = item.ID }, new { onclick = " return confirm('您真的打算删除吗?'); " })
</td>
</tr>
}
}
else
{
<tr>
<td colspan="8">
没有满足条件的记录!
</td>
</tr>
}
</table>
<div class="pager">
@Html.Raw(Html.Pager(Model.PageIndex, Model.PageSize, Model.TotalCount, Model.PageIndex))
</div>

浙公网安备 33010602011771号