We’ve all seen the example “list” actions that return in every row. Sure they are easy to code but also the in real world how often can you get away with that? Most of times you will want to use paging in your results so the user only sees a limited number of results at a time. Luckily there’s a NuGet package for that. It’s called PagedList.Mvc and it uses the PagedList by the same author.

asp net mvc

To start you will need to install the package using the NuGet package manager in visual studio.
1
PM> install-package PagedList.MVC
This will add a few things to your project.
  1. Your application will now reference PagedList and PagedList.Mvc assemblies
  2. In the Content folder you will see a new cascading style sheet called PagedList.css
  3. In the Scripts folder you will find a new folder called PagedList with Javascript file and Template file
Now you’ve added PagedList.Mvc to your application using it is pretty trivial. You’ll need to use the PagedList namespace. Then add a new parameter to your list action (Index in our example) that accepts a page number. I always default the page number to 1 so that it will work if called without a page number. Finally you’
1
2
3
4
5
6
7
8
9
10
11
12
13
public ActionResult Index(int page = 1)
{
    // I do this just in case someone tries to put in 0 or a negative number
    if (page < 1)
    {
        page = 1;
    }
 
    IQueryable<Product> products = MyRepository.FindAllProducts();
    IPagedList<Product> productPage = products.ToPagedList(page, 5);
 
    return View(productPage);
}

What about our view?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
@model IPagedList<Product>
@{
    ViewBag.Title = "List";
}
@using PagingDemo.Models;
@using PagedList.Mvc;
@using PagedList;
 
<html>
<head>
    <title>Paged List Demo</title>
    <link href="../../Content/PagedList.css" type="text/javascript" rel="Stylesheet" />
</head>
<body>
<h2>Products</h2>
 
<table>
    <thead>
        <tr>
            <th>#</th>
            <th>Name</th>
            <th>Price</th>
        </tr>
    </thead>
    <tbody>
    @foreach (Product p in Model)
    {
        <tr>
            <td>@p.ID</td>
            <td>@p.Name</td>
            <td>@p.Price</td>
        </tr>
    }
    </tbody>
</table>
 
@Html.PagedListPager(Model, page => Url.Action("Index", new { page }))
</body>
</html>

Post a Comment

 
Top