最近寫了一個mvc 的 分頁,樣式是基於 bootstrap 的 ,提供查詢條件,不過可以自己寫樣式根據個人的喜好,以此分享一下。首先新建一個Mvc 項目,既然是分頁就需要一些數據,我這 邊是模擬了一些假的數據,實際的項目中都是在數據庫中去取得的,很簡單的數據:
public class User
{
public string Name { get; set; }
public int Age { get; set; }
}
取數據我這邊是加了120個數據:
public List<User> GetData()
{
List<User> list = new List<User>();
string[] array = new string[]{ "Tom", "Joy", "James", "Kobe", "Jodan","LiLei", "Hanmeimei", "xiaoming","Danneil", "Forest", "Newbee", "Azure" };
for (int i = 0; i < 120; i++)
{
User user = new User();
user.Age = i;
user.Name = array[i / 10];
list.Add(user);
}
return list;
}
然后新建一個 PageModel類
/// <summary>
/// 有些屬性我寫成了虛的, 這樣可以根據不同的需要去重寫便於擴展
/// </summary>
public class BasePageModel
{
public string SearchKeyWord { get; set; }
/// <summary>
///點擊分頁是指向 Action 的名字 根據具體需要而定
/// </summary>
public virtual string ActionName
{
get
{
return "Index";
}
}
public int TotalCount { get; set; }
public int CurrentIndex { get; set; }
public int TotalPages
{
get
{
return (int)Math.Ceiling((double)TotalCount / (double)PageSize);
}
}
/// <summary>
/// 根據需要具體而定PageSize
/// </summary>
public virtual int PageSize
{
get { return 10; }
}
/// <summary>
///根據需要具體而定 分頁顯示最大的頁數
/// </summary>
public virtual int DisplayMaxPages
{
get
{
return 10;
}
}
public bool IsHasPrePage
{
get
{
return CurrentIndex != 1;
}
}
public bool IsHasNextPage
{
get
{
return CurrentIndex != TotalPages;
}
}
}
再新建一個分布式圖 建在Shared 文件夾里,代碼如下:
@using MvcTest.Models
@model MvcTest.Models.BasePageModel
@{if (Model != null && Model.TotalPages != 0)
{
<ul class="pagination">
@{
@Url.CreatPageLiTag(Model, Model.CurrentIndex - 1, false, Model.IsHasPrePage, "«")
if (Model.TotalPages <= Model.DisplayMaxPages)
{
for (int i = 1; i < Model.TotalPages; i++)
{
@Url.CreatPageLiTag(Model, i, i == Model.CurrentIndex);
}
}
else
{
if (Model.CurrentIndex - 1 < 5)
{
for (int i = 1; i <= Model.DisplayMaxPages - 1; i++)
{
@Url.CreatPageLiTag(Model, i, i == Model.CurrentIndex);
}
@Url.CreatPageLiTag(Model, Model.CurrentIndex, false, false, "...");
}
else
{
@Url.CreatPageLiTag(Model, 1);
if (Model.CurrentIndex + (Model.DisplayMaxPages - 2) / 2 >= Model.TotalPages)
{
int page = Model.CurrentIndex - (Model.DisplayMaxPages - Model.TotalPages + Model.CurrentIndex - 1);
if (page > 1)
{
@Url.CreatPageLiTag(Model, Model.CurrentIndex, false, false, "...");
}
for (int i = page + 1; i < Model.TotalPages; i++)
{
@Url.CreatPageLiTag(Model, i, i == Model.CurrentIndex);
}
}
else
{
int page = Model.CurrentIndex - (Model.DisplayMaxPages - 2) / 2;
if (page > 2)
{
@Url.CreatPageLiTag(Model, Model.CurrentIndex, false, false, "...");
}
for (int i = page; i < Model.CurrentIndex + (Model.DisplayMaxPages - 2) / 2; i++)
{
@Url.CreatPageLiTag(Model, i, i == Model.CurrentIndex);
}
@Url.CreatPageLiTag(Model, Model.CurrentIndex, false, false, "...");
}
}
}
@Url.CreatPageLiTag(Model, Model.TotalPages, Model.TotalPages == Model.CurrentIndex)
@Url.CreatPageLiTag(Model, Model.CurrentIndex + 1, false, Model.IsHasNextPage, "»")
}
</ul>
}
}
以上就是分頁的核心代碼,包括了一些判斷邏輯,其中的 @Url.CreatPageLiTag 我是寫了一個擴展
public static class HtmlHelperExtensions
{
public static MvcHtmlString CreatPageLiTag(this UrlHelper urlHelper,
BasePageModel pageModel,
int index,
bool isCurrentIndex = false,
bool isDisable = true,
string content = "")
{
string url = urlHelper.Action(pageModel.ActionName, new { searchkey = pageModel.SearchKeyWord, index = index });
string activeClass = !isCurrentIndex ? string.Empty : "class='active'";
string disableClass = isDisable ? string.Empty : "class='disabled'";
url = isDisable ? "href='" + url + "'" : string.Empty;
string contentString = string.IsNullOrEmpty(content) ? index.ToString() : content;
return new MvcHtmlString("<li " + activeClass + disableClass + "><a " + url + ">" + contentString + "</a></li>");
}
}
在這里面里面 是生成<a/>標簽的,樣式可以自己定。無非就是一些css 的定義。
然后就在action 的方法里取數據
public ActionResult Index(string searchkey, string index)
{
if (string.IsNullOrEmpty(index))
index = "1";
if (string.IsNullOrEmpty(searchkey))
searchkey = string.Empty;
List<User> totalList = GetData().Where(p=>p.Name.ToLower().Contains(searchkey.ToLower())).ToList();
BasePageModel page = new BasePageModel() { SearchKeyWord = searchkey, CurrentIndex = Int32.Parse(index), TotalCount = totalList.Count };
List<User> pageList = totalList.Skip((page.CurrentIndex - 1) * page.PageSize).Take(page.PageSize).ToList();
ViewData["pagemodel"] = page;
return View(pageList);
}
前台代碼:
@model List<MvcTest.Controllers.User>
@{
ViewBag.Title = "Index";
}
<h2>Data List</h2>
<form class="navbar-form navbar-right" name="searchform" action="@Url.Action("Index", new {index="1" }) method="post">
<div class="input-group">
<input type="text" id="searchkey" name="searchkey" class="form-control" placeholder="Search..." />
<span class="btn input-group-addon" onclick="document.searchform.submit();">
<span class="glyphicon glyphicon-search"></span>
</span>
</div>
</form>
<table class="table table-hover table-bordered table-condensed">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>@item.Name</td>
<td>@item.Age</td>
</tr>
}
</tbody>
</table>
@Html.Partial("MvcPagerView", ViewData["pagemodel"])
Ok 搞定。效果如下: