我使用了Nerddinner教程的分页示例。但我也想添加页码,如下所示:
<<< 1 2 3 4 5 6 >>>
如果我从 0 而不是从 1 开始分页,则下面的代码有效。我该如何解决这个问题?
这是我的代码:
分页列表.cs
public class PaginatedList<T> : List<T> {
public int PageIndex { get; private set; }
public int PageSize { get; private set; }
public int TotalCount { get; private set; }
public int TotalPages { get; private set; }
public PaginatedList(IQueryable<T> source, int pageIndex, int pageSize) {
PageIndex = pageIndex;
PageSize = pageSize;
TotalCount = source.Count();
TotalPages = (int) Math.Ceiling(TotalCount / (double)PageSize);
this.AddRange(source.Skip(PageIndex * PageSize).Take(PageSize));
}
public bool HasPreviousPage {
get {
return (PageIndex > 0);
}
}
public bool HasNextPage {
get {
return (PageIndex+1 < TotalPages);
}
}
}
用户控制器.cs
public ActionResult List(int? page)
{
const int pageSize = 20;
IUserRepository userRepository = new UserRepository();
IQueryable<User> listUsers = userRepository.GetAll();
PaginatedList<User> paginatedUsers = new PaginatedList<User>(listUsers, page ?? 0, pageSize);
return View(paginatedUsers);
}
列表.cshtml
@if (Model.HasPreviousPage)
{
@Html.RouteLink(" Previous ", "PaginatedUsers", new { page = (Model.PageIndex - 1) })
}
@for (int i = 1; i <= Model.TotalPages; i++)
{
@Html.RouteLink(@i.ToString(), "PaginatedUsers", new { page = (@i ) })
}
@if (Model.HasNextPage)
{
@Html.RouteLink(" Next ", "PaginatedUsers", new { page = (Model.PageIndex + 1) })
}