views:

360

answers:

3

i have an asp.net website where i do paging through on the code behind using:

 PagedDataSource objPds = new PagedDataSource
                              {
                                  DataSource = ds.Tables[0].DefaultView,
                                  AllowPaging = true,
                                  PageSize = 12
                              };

what is the equivalent best way of doing paging for asp.net-mvc. I would think this would actually belong in the view code.

+9  A: 

I would just define a custom route with the page number in it:

routes.MapRoute(
                "Books", // Route name
                "books/{page}", // URL with parameters
                new {controller = "Books", action = "List", page = 1}
                );

Will give you this kind of Url:

http://localhost/books/4/

Then in your controller action you get this page number:

public BooksController
{
    public ActionResult List (int page)
    {
        /* Retrieve records for the requested page from the database */

        return View ();
    }
}

So your view will not actually be aware of the current page. It will just display a list of supplied records.

You will also need to generate links to various pages either in this view directly or maybe in your master page.

Developer Art
+4  A: 

There is a good paging class example in the Nerd Dinner project:

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);
            }
        }
CD
A: 

If you buy:
Professional ASP.NET MVC 1.0 (Wrox Programmer to Programmer)

The section in there about Ajax and JsonResult ... very good walkthrough of how to set up both an javascript and non-javascript solution. I haven't actually implemented it, so I don't remember too much about it, I just remember when I read it, I thought it would work perfectly for paging on my new site.

Decent tutorial here as well:
http://www.asp.net/learn/mvc/tutorial-32-cs.aspx

Martin