Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I do pagination in ASP.NET MVC?

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) {    //... } 
like image 542
Spoike Avatar asked Jan 15 '09 09:01

Spoike


People also ask

What is .NET pagination?

Paging or Pagination in a method in which you get paged response. This means that you request with a page number and page size, and the ASP.NET Core WebApi returns exactly what you asked for, nothing more.

How can we implement pagination in asp net core?

How to implement paging in ASP.NET Core Web API. In an empty project, update the Startup class to add services and middleware for MVC. Add models to hold link and paging data. Create a type to hold the paged list.

What is PagedList MVC?

Pagination is a common requirement in a web application when it comes to show records from the databases or a static source. here we are going to do the pagination in MVC using PagedList nuget package. First create the MVC project and add a controller method to display the data records.


1 Answers

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 }) %> 
like image 123
Marc Gravell Avatar answered Oct 13 '22 21:10

Marc Gravell