基於Bootstrap的Asp.net Mvc 分頁的實現

  最近寫了一個mvc 的 分頁,樣式是基於 bootstrap 的 ,提供查詢條件,不過可以自己寫樣式根據個人的喜好,以此分享一下。首先新建一個Mvc 項目,既然是分頁就需要一些數據,我這邊是模擬了一些假的數據,實際的項目中都是在數據庫中去取得的,很簡單的數據:

1  public class User
2     {
3         public string Name { get; set; }
4 
5         public int Age { get; set; }
6     }

取數據我這邊是加了120個數據:

 1   public List<User> GetData()
 2         {
 3             List<User> list = new List<User>();
 4             string[] array = new string[] { "Tom", "Joy", "James", "Kobe", "Jodan", "LiLei", "Hanmeimei", "xiaoming", "Danneil", "Forest", "Newbee", "Azure" };
 5             for (int i = 0; i < 120; i++)
 6             {
 7                 User user = new User();
 8                 user.Age = i;
 9                 user.Name = array[i / 10];
10                 list.Add(user);
11             }
12 
13 
14             return list;
15         }

 然後新建一個 PageModel類

 1 /// <summary>
 2     /// 有些屬性我寫成了虛的, 這樣可以根據不同的需要去重寫便於擴展
 3     /// </summary>
 4     public class BasePageModel
 5     {
 6         public string SearchKeyWord { get; set; }
 7 
 8         /// <summary>
 9         ///點擊分頁是指向 Action 的名字 根據具體需要而定
10         /// </summary>
11         public virtual string ActionName
12         {
13             get
14             {
15                 return "Index";
16             }
17         }
18 
19         public int TotalCount { get; set; }
20 
21         public int CurrentIndex { get; set; }
22 
23         public int TotalPages
24         {
25             get
26             {
27                 return (int)Math.Ceiling((double)TotalCount / (double)PageSize);
28             }
29         }
30              
31         /// <summary>
32         /// 根據需要具體而定PageSize
33         /// </summary>
34         public virtual int PageSize
35         {
36             get { return 10; }
37         }
38 
39         /// <summary>
40         ///根據需要具體而定 分頁顯示最大的頁數 
41         /// </summary>
42         public virtual int DisplayMaxPages
43         {
44             get
45             {
46                 return 10;
47             }
48         }
49 
50         public bool IsHasPrePage
51         {
52             get
53             {
54                 return CurrentIndex != 1;
55             }
56         }
57 
58         public bool IsHasNextPage
59         {
60             get
61             {
62                 return CurrentIndex != TotalPages;
63             }
64         }
65     }

再新建一個分佈式圖 建在Shared 文件夾裏,代碼如下:

 1 @using MvcTest.Models
 2 @model MvcTest.Models.BasePageModel
 3 
 4 @{if (Model != null && Model.TotalPages != 0)
 5 {
 6     <ul class="pagination">
 7         @{
 8 
 9             @Url.CreatPageLiTag(Model, Model.CurrentIndex - 1, false, Model.IsHasPrePage, "&laquo;")
10 
11     if (Model.TotalPages <= Model.DisplayMaxPages)
12     {
13         for (int i = 1; i < Model.TotalPages; i++)
14         {
15             @Url.CreatPageLiTag(Model, i, i == Model.CurrentIndex);
16         }
17     }
18     else
19     {
20         if (Model.CurrentIndex - 1 < 5)
21         {
22             for (int i = 1; i <= Model.DisplayMaxPages - 1; i++)
23             {
24                 @Url.CreatPageLiTag(Model, i, i == Model.CurrentIndex);
25             }
26 
27             @Url.CreatPageLiTag(Model, Model.CurrentIndex, false, false, "...");
28         }
29         else
30         {
31             @Url.CreatPageLiTag(Model, 1);
32 
33 
34           if (Model.CurrentIndex + (Model.DisplayMaxPages - 2) / 2 >= Model.TotalPages)
35           {
36               int page = Model.CurrentIndex - (Model.DisplayMaxPages - Model.TotalPages + Model.CurrentIndex - 1);
37 
38               if (page > 1)
39               {
40                @Url.CreatPageLiTag(Model, Model.CurrentIndex, false, false, "...");
41               }
42 
43               for (int i = page + 1; i < Model.TotalPages; i++)
44               {
45                  @Url.CreatPageLiTag(Model, i, i == Model.CurrentIndex);
46                }
47             }
48          else
49            {
50               int page = Model.CurrentIndex - (Model.DisplayMaxPages - 2) / 2;
51 
52                if (page > 2)
53                {
54                  @Url.CreatPageLiTag(Model, Model.CurrentIndex, false, false, "...");
55                }
56 
57                 for (int i = page; i < Model.CurrentIndex + (Model.DisplayMaxPages - 2) / 2; i++)
58                 {
59                   @Url.CreatPageLiTag(Model, i, i == Model.CurrentIndex);
60                  }
61                 @Url.CreatPageLiTag(Model, Model.CurrentIndex, false, false, "...");
62          }
63 
64         }
65     }
66 
67     @Url.CreatPageLiTag(Model, Model.TotalPages, Model.TotalPages == Model.CurrentIndex)
68     @Url.CreatPageLiTag(Model, Model.CurrentIndex + 1, false, Model.IsHasNextPage, "&raquo;")
69 
70         }
71     </ul>
72 
73 }}

以上就是分頁的核心代碼,包括了一些判斷邏輯,其中的 @Url.CreatPageLiTag 我是寫了一個擴展

 1 public static class HtmlHelperExtensions
 2     {
 3         public static MvcHtmlString CreatPageLiTag(this UrlHelper urlHelper,
 4                                                    BasePageModel pageModel,
 5                                                    int index,
 6                                                    bool isCurrentIndex = false,
 7                                                    bool isDisable = true,
 8                                                    string content = "")
 9         {
10 
11             string url = urlHelper.Action(pageModel.ActionName, new { searchkey = pageModel.SearchKeyWord, index = index });
12             string activeClass = !isCurrentIndex ? string.Empty : "class='active'";
13             string disableClass = isDisable ? string.Empty : "class='disabled'";
14             url = isDisable ? "href='" + url + "'" : string.Empty;
15             string contentString = string.IsNullOrEmpty(content) ? index.ToString() : content;
16 
17             return new MvcHtmlString("<li " + activeClass + disableClass + "><a " + url + ">" + contentString + "</a></li>");
18         }
19     }

在這裏面裏面 是生成<a/>標籤的,樣式可以自己定。無非就是一些css 的定義。

然後就在action 的方法裏取數據

 1   public ActionResult Index(string searchkey, string index)
 2         {
 3             if (string.IsNullOrEmpty(index))
 4                 index = "1";
 5             if (string.IsNullOrEmpty(searchkey))
 6                 searchkey = string.Empty;
 7 
 8             List<User> totalList = GetData().Where(p=>p.Name.ToLower().Contains(searchkey.ToLower())).ToList();
 9             BasePageModel page = new BasePageModel() { SearchKeyWord = searchkey, CurrentIndex = Int32.Parse(index), TotalCount = totalList.Count };
10 
11             List<User> pageList = totalList.Skip((page.CurrentIndex - 1) * page.PageSize).Take(page.PageSize).ToList();
12             ViewData["pagemodel"] = page;
13             return View(pageList);
14         }

前臺代碼:

 1 @model List<MvcTest.Controllers.User>
 2 @{
 3     ViewBag.Title = "Index";
 4 }
 5 
 6 <h2>Data List</h2>
 7 <form class="navbar-form navbar-right" name="searchform" action="@Url.Action("Index", new {index="1" }) method="post">
 8     <div class="input-group">
 9         <input type="text" id="searchkey" name="searchkey" class="form-control" placeholder="Search..." />
10         <span class="btn input-group-addon" onclick="document.searchform.submit();">
11             <span class="glyphicon  glyphicon-search"></span>
12         </span>
13     </div>
14 </form>
15 <table class="table  table-hover table-bordered  table-condensed">
16     <thead>
17         <tr>
18             <th>Name</th>
19             <th>Age</th>
20         </tr>
21     </thead>
22     <tbody>
23         @foreach (var item in Model)
24         {
25             <tr>
26                 <td>@item.Name</td>
27                 <td>@item.Age</td>
28             </tr>
29         }
30 
31     </tbody>
32 </table>
33 @Html.Partial("MvcPagerView", ViewData["pagemodel"])

 

 

Ok 搞定。效果如下:

 

分頁的樣式我還是比較喜歡的,當然可以自己擴展。