0

我使用了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) })
} 
4

3 回答 3

1

分页列表.cs

.Skip((PageIndex -1) * PageSize).Take(PageSize)

用户控制器.cs

public ActionResult List(int page = 1)
{
于 2012-05-30T22:33:01.297 回答
0

我做了这个改变:

分页列表.cs

public PaginatedList(IQueryable<T> source, int pageIndex, int pageSize) {
        .
        .
        .
        this.AddRange(source.Skip((PageIndex -1) * PageSize).Take(PageSize));
    }

public bool HasPreviousPage {
        get {
            return (PageIndex > 1);
        }
    }

    public bool HasNextPage {
        get {
            return (PageIndex < TotalPages);
        }
    }

用户控制器.cs

    public ActionResult List(int? page)
    {
        const int pageSize = 20;

        page = (page < 1) ? 1 : page ?? 0;
        .
        .
        .
于 2012-05-31T07:57:19.320 回答
0

我建议使用库而不是编写自己的分页代码。MvcPaging是这些库之一。

在这里查看我的答案 -使用哪些好的库来对自定义 html(不是基于表格)进行分页?

于 2012-05-31T08:26:13.657 回答