[英]Minimizing paging links in Asp.Net MVC
我為此苦苦掙扎了一段時間。 今天,我終於編寫了以下代碼。
ViewModel包含一個int
屬性,該屬性稍后可以告訴視圖數據已拆分為多少頁。
控制器通過采用指定的行數來拆分數據,並且在進行分頁時,按pageNumber * recordsPerPage
看一看:
ViewModel
public class ThreadPostsViewModel
{
public Thread Thread { get; set; }
public List<Post> Posts { get; set; }
public int Pages { get; set; }
}
控制器
private int PostsPerPage = 10;
public ActionResult Thread(int id, int page = 1)
{
using (OrtundEntities Db = new OrtundEntities())
{
// get the thread and its parent data (parent for breadcrumbs)
var Thread = Db.Threads.Include(t => t.Title).FirstOrDefault(x => x.Id == id);
// create a list for the Posts
List<Post> Posts = new List<Post>();
// select based on paging
if (page == 1)
// no paging has happened, get the first set of records
Posts = Db.Posts.Include(x => x.User).Where(x => x.ThreadId == id).OrderByDescending(x => x.Date).Take(PostsPerPage).ToList();
else
// we're on a new page. Skip however many rows we've already seen
Posts = Db.Posts.Include(x => x.User).Where( x=> x.ThreadId == id).OrderByDescending(x => x.Date).Take(PostsPerPage).Skip(PostsPerPage * page).ToList();
// create and return the view model
ThreadPostsViewModel Model = new ThreadPostsViewModel
{
Thread = Thread,
Posts = Posts,
Pages = Posts.Count / PostsPerPage
};
return View(Model);
}
}
風景
@model Ortund.Models.ThreadPostsViewModel
<div class="paging">
@for (int i = 1; i < Model.Pages; i++)
{
string Url = String.Format("/View/Thread/{0}?page={1}", Model.Thread.Id, i);
<a href="@Url">@i</a>
}
</div>
<div class="posts-list">
@foreach (var Post in Model.Posts)
{
<div class="post" id="@Post.Id">
</div>
}
</div>
在此代碼中,假設從數據庫中選擇了300個帖子,並且每頁指定10個帖子,那么應該有30個頁面。
即使這是適合您頁面設計的大量鏈接,所以我如何才能最小化這些分頁鏈接並僅顯示10個分頁鏈接,當您要說第8頁時,這些鏈接會更改為顯示3- 13,例如?
甚至使分頁鏈接顯示如下也是比較可取的:
1 2 3 4 5 ... 90 91 92 93 94
在控制器中放置當前頁面的值:
ViewBag.currentPage = page;
鑒於您可以執行以下操作(未測試):
<div class="paging">
@if (Model.Pages > 11 && ViewBag.currentPage > 6)
{
for (int i = ViewBag.currentPage - 6; i < ViewBag.currentPage -1; i++)
{
string Url = String.Format("/View/Thread/{0}?page={1}", Model.Thread.Id, i);
<a href="@Url">@i</a>
}
for (int i = ViewBag.currentPage + 1; i < ViewBag.currentPage + 6; i++)
{
string Url = String.Format("/View/Thread/{0}?page={1}", Model.Thread.Id, i);
<a href="@Url">@i</a>
}
}
else
{
for (int i = 1; i < Model.Pages; i++)
{
string Url = String.Format("/View/Thread/{0}?page={1}", Model.Thread.Id, i);
<a href="@Url">@i</a>
}
}
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.