Search code examples
asp.netasp.net-mvcpagination

paging in asp.net mvc


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.


Solution

  • 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.