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) { //... }
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 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.
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.
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 }) %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With