我已经挣扎了很长一段时间。今天我终于写了下面的代码。
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
答案 0 :(得分:1)
在当前页面的控制器放置值中:
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>