本文主要做了一个HtmHelper类的分页扩展函数,方便在视图中调用,有需要的朋友可以参考一下,希望对大家有所帮助。
1、扩展HtmlHelper类方法ShowPageNavigate
output.Append(" ");}if (currentPage < totalPages){//处理下一页的链接output.AppendFormat("下一页 ", redirectTo, currentPage &#43; 1, pageSize);}output.Append(" ");if (currentPage !&#61; totalPages){output.AppendFormat("末页 ", redirectTo, totalPages, pageSize);}output.Append(" ");}output.AppendFormat("", currentPage, totalPages);//这个统计加不加都行return new HtmlString(output.ToString());
}
2、添加公共类PagerInfo,PageQuery
public class PagerInfo
{public int RecordCount { get; set; }public int CurrentPageIndex { get; set; }public int PageSize { get; set; }
}public class PagerQuery
{public PagerQuery(TPager pager, TEntityList entityList){this.Pager &#61; pager;this.EntityList &#61; entityList;}public TPager Pager { get; set; }public TEntityList EntityList { get; set; }
}
3、然后在Controller里面添加Action
public ActionResult Index(int? pageSize, int? pageIndex)
{int pageIndex1 &#61; pageIndex ?? 1;int pageSize1 &#61; pageSize ?? 5;int count &#61; 0;//从数据库在取得数据&#xff0c;并返回总记录数var temp &#61; newsSer.LoadPageEntities(c &#61;> true, c &#61;> c.id, false, pageSize1, pageIndex1, out count);PagerInfo pager &#61; new PagerInfo();pager.CurrentPageIndex &#61; pageIndex1;pager.PageSize &#61; pageSize1;pager.RecordCount &#61; count;PagerQuery
}
4、View里的部分代码
5、添加一些样式
.paginator
{font: 12px Arial, Helvetica, sans-serif;padding: 10px 20px 10px 0;margin: 0px auto;
}.paginator a
{border: solid 1px #ccc;color: #0063dc;cursor: pointer;text-decoration: none;
}.paginator a:visited
{padding: 1px 6px;border: solid 1px #ddd;background: #fff;text-decoration: none;
}.paginator .cpb
{border: 1px solid #F50;font-weight: 700;color: #F50;background-color: #ffeee5;
}.paginator a:hover
{border: solid 1px #F50;color: #f60;text-decoration: none;
}.paginator a, .paginator a:visited, .paginator .cpb, .paginator a:hover
{float: left;height: 16px;line-height: 16px;min-width: 10px;_width: 10px;margin-right: 5px;text-align: center;white-space: nowrap;font-size: 12px;font-family: Arial,SimSun;padding: 0 3px;
}.paginator label
{display:block; float:left;
}
6.总结
这个案例简单实现了在MVC中快速分页&#xff0c;其实很多开源的项目中都有相关的HtmlHepler的扩展函数&#xff0c;其中也不乏带有分页的扩展&#xff0c;例如著名的开源商城项目nopCommerce&#xff0c;其中有就一个HtmlExtensions.cs扩展类&#xff0c;里面就有关于分页的扩展&#xff0c;人家写的可是相当专业哦&#xff0c;有兴趣的可以研究一下。