views:

3700

answers:

3

What is the most preferred and easiest way to do pagination in ASP.NET MVC? I.e. what is the easiest way to break up a list into several browsable pages.

As an example lets say I get a list of elements from a database/gateway/repository like this:

public ActionResult ListMyItems()
{
    List<Item> list = ItemDB.GetListOfItems();
    ViewData["ItemList"] = list;

    return View();
}

For simplicity's sake I'd like to specify just a page number for my action as parameter. Like this:

public ActionResult ListMyItems(int page)
{
   //...
}
+16  A: 

Well, what is the data source? Your action could take a few defaulted arguments, i.e.

ActionResult Search(string query, int startIndex, int pageSize) {...}

defaulted in the routes setup so that startIndex is 0 and pageSize is (say) 20:

        routes.MapRoute("Search", "Search/{query}/{startIndex}",
                        new
                        {
                            controller = "Home", action = "Search",
                            startIndex = 0, pageSize = 20
                        });

To split the feed, you can use LINQ quite easily:

var page = source.Skip(startIndex).Take(pageSize);

(or do a multiplication if you use "pageNumber" rather than "startIndex")

With LINQ-toSQL, EF, etc - this should "compose" down to the database, too.

You should then be able to use action-links to the next page (etc):

<%=Html.ActionLink("next page", "Search", new {
                query, startIndex = startIndex + pageSize, pageSize }) %>
Marc Gravell
That's an interesting routing example, so I'll upvote it. I haven't gotten into the groove of using LINQ yet, so Skip and Take is new to me. But that's definately what I need. And that's why I'll mark this as answer.
Spoike
awsome stuff! Thank you very much in deed.
Ric Tokyo
+5  A: 

I had the same problem and found a very elegant solution for a Pager Class from

http://blogs.taiga.nl/martijn/2008/08/27/paging-with-aspnet-mvc/

In your controller the call looks like:

return View(partnerList.ToPagedList(currentPageIndex, pageSize));

and in your view:

<div class="pager">
    Seite: <%= Html.Pager(ViewData.Model.PageSize, 
                          ViewData.Model.PageNumber,
                          ViewData.Model.TotalItemCount)%>
</div>
Oliver
It's for ASP.NET MVC Preview 5. Will it work for ASP.NET MVC Beta?
Spoike
Link changed, code updated to RC1 (guess it will work with 1.0 too, will try out now).http://blogs.taiga.nl/martijn/2008/08/27/paging-with-aspnet-mvc/
Palantir
A: 

Curious how I get the startIndex and pageSize within the view. I'm getting a "Compiler Error Message: CS0103: The name 'startIndex' does not exist in the current context" error

Dave