In this recipe, we will take a look at how you can create and display a pageable set of data. We will also see how we can navigate to the next and previous pages of data.
Because this recipe is not so much about how to run queries as it is about how to display a page of data and navigate to the next and previous pages, we will use NBuilder to mock our data access. We will also continue to use our Product
and ProductRepository
classes as the data to work with.
Product
and ProductRepository
classes from the previous recipes. ProductRepository
to add the pagination functionality. First, we need to add two parameters to our GetProducts
method. We will need a Page
parameter to tell us what page of data we need to display, and we will need a RecordCount
to tell us how much data to return for each page.Models/ProductRepository.cs:
public List<Product> GetProducts(int page, int recordCount) { ...
Models/ProductRepository.cs:
public List<Product> GetProducts(int page, int recordCount) { if (Page < 1) Page = 1;
Build()
method and before the ToList()
call.Models/ProductRepository.cs:
... .Build() //skip the appropriate amount of records .Skip((page - 1) * recordCount) .ToList(); ...
ProductRepository
updated, we can now update our controller to work with the new GetProducts
signature. We will also specify the default record count to be used by our ProductRepository
. We will also pass the page ID down to our view to play with later.Controllers/HomeController.cs:
private int RecordCount = 20; public ActionResult Index(int id = 1) { ViewData["Products"] = new ProductRepository().GetProducts( id, RecordCount); ViewData["id"] = id; return View(); }
Views/Home/Index.aspx:
<fieldset> <legend>Products</legend> <% int id = (int) ViewData["id"]; int PreviousId = (id - 1) < 1 ? 1 : id - 1; int NextId = id + 1; %> <%= Html.ActionLink("Previous","Index",new {@id=PreviousId}) %> - <%= Html.ActionLink("Next","Index",new {@id=NextId}) %>
The key to this recipe is knowing how big the set of data is you want to work with, and which page you are currently on. Tracking this, as people navigate from one page of data to the next, is all that is really required. Once you have tracked where you are and how big the page set is, you then need a way for your users to go forward and backward within that set of data. Other than that, you need to be able to communicate these needs with your data, be it XML, files, objects, or relational data in a database.