How to make paging start from 1 instead of 0 in ASP.NET MVC

Posted by ssx on Stack Overflow See other posts from Stack Overflow or by ssx
Published on 2012-05-30T22:30:01Z Indexed on 2012/05/30 22:40 UTC
Read the original article Hit count: 141

Filed under:
|

I used the paging example of the Nerddinner tutorial. But I also wanted to add page Numbers, somehting like that:

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

The code below works if i start my paging from 0, but not from 1. How can I fix this ?

Here is my code:

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

© Stack Overflow or respective owner

Related posts about c#

Related posts about asp.net-mvc