HtmlHelper扩展
1 namespace POS.UI.HtmlHelpers
2 {
3 public static class PagingHelper
4 {
5 public static MvcHtmlString PageLinks(this HtmlHelper html, PagingInfo pagingInfo, Func<int, string> pageUrl)
6 {
7 StringBuilder result = new StringBuilder();
8 for (int i = 1; i <= pagingInfo.TotalPages; i++)
9 {
10 TagBuilder tag = new TagBuilder("a");
11 tag.MergeAttribute("href", pageUrl(i));
12 tag.InnerHtml = i.ToString();
13 if (i == pagingInfo.CurrentPage)
14 {
15 tag.AddCssClass("selected");
16 tag.AddCssClass("btn-primary");//用到的是Bootstrap的样式
17 }
18 tag.AddCssClass("btn btn-default");
19 result.Append(tag.ToString());
20 }
21 return MvcHtmlString.Create(result.ToString());
22 }
23 }
24 }
PageInfo类
1 namespace POS.UI.Models
2 {
3 public class PagingInfo
4 {
5 public int TotalItems { get; set; }
6 public int ItemsPerPage { get; set; }
7 public int CurrentPage { get; set; }
8 public int TotalPages {
9 get { return (int)Math.Ceiling(((decimal)TotalItems/ItemsPerPage)); }
10 }
11 }
12 }
ViewModel
1 namespace POS.UI.Models
2 {
3 public class IndexViewModel
4 {
5 public IEnumerable<Goods> GoodsCollection { get; set; }
6 public PagingInfo PagingInfo { get; set; }
7 }
8 }
调用示例
1 <div class="btn-group pull-right">
2 @Html.PageLinks(Model.PagingInfo, x => Url.Action("Index", new { page = x }))
3 </div>