如何使分页从1而不是0开始

时间:2012-05-30 22:30:02

标签: c# asp.net-mvc

我使用了Nerddinner教程的分页示例。但是我也想添加页码,就像那样:

  

<<< 1 2 3 4 5 6>>>

如果我从0开始分页,而不是从1开始分页,则下面的代码有效。如何解决此问题?

这是我的代码:

PaginatedList.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);
        }
    }
}

UserController.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);
    }

List.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) })
} 

3 个答案:

答案 0 :(得分:1)

PaginatedList.cs

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

UserController.cs

public ActionResult List(int page = 1)
{

答案 1 :(得分:0)

我做了这些改变:

<强> PaginatedList.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);
        }
    }

<强> UserController.cs

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

        page = (page < 1) ? 1 : page ?? 0;
        .
        .
        .

答案 2 :(得分:0)

我建议使用库而不是编写自己的分页代码。 MvcPaging是其中一个图书馆。

请在此处查看我的回答 - what good libraries to use for paging on custom html (not table based)?