ASP.NET MVC > Entity Framework

Pagination of records in ASP.NET MVC

How to paginate records in the ASP.NET MVC view?

Pagination is useful when we have to list more number of records from the database so that all records doesn’t show in one page. Clicking on page numbers show records for that page so that it’s easy for users to navigate all records.

As ASP.NET MVC doesn’t have much efficient and easy mechanism to paginate records from the database, we will use a plugin named PagedList.

Search PagedList using search box and click on Install. Remember to install both PagedList and PagedList.Mvc.

This adds PagedList.dll, PagedList.Mvc.dll into the bin folder and also PagedList.css into ~/Content folder.

Now create a method called Paging in the controller class.


using PagedList;
        public ActionResult Paging(int page = 1)
            int recordsPerPage = 2;

            var list = db.PersonalDetails.ToList().ToPagedList(page, recordsPerPage);
            return View(list);

This method accepts page as parameter and it’s default value is 1. When we use PagedList namespace, it gives us ToPagedList method that accepts page and record per page as parameter.

Now we need few change in the View.


@using PagedList; 
@using PagedList.Mvc;
@model IPagedList<WebApplication1.Models.PersonalDetail> <p> @Html.ActionLink("Create New", "Create") </p> <table class="table"> <tr> <th>First Name </th> <th>Last Name </th> <th>Age </th> <th>Active </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td>@Html.DisplayFor(modelItem => item.FirstName) </td> <td>@Html.DisplayFor(modelItem => item.LastName) </td> <td>@Html.DisplayFor(modelItem => item.Age) </td> <td>@Html.DisplayFor(modelItem => item.Active) </td> <td>@Html.ActionLink("Edit", "Edit", new { id=item.AutoId }) | @Html.ActionLink("Details", "Details", new { id=item.AutoId }) | @Html.ActionLink("Delete", "Delete", new { id=item.AutoId }) </td> </tr> } </table> <div class="pagedList"> @Html.PagedListPager(Model, page => Url.Action("Paging", new { page }), PagedListRenderOptions.PageNumbersOnly) </div>

Notice the @using directive where we have used PagedList and PagedList.Mvc. And also @model directive is not IEnumerable any more but it is IPagedList.

Note that from the heading part of each column we have removed @DisplayNameFor method and hard coded the heading as @DisplayNameFor is not supported by IPagedList.

Now look carefully the highlighted code in the last of the view that is rendering the Page numbers by using @Html.PagedListPager method by passing the action method to redirect to with the current page and type of pagination to use. This renders view like below. Trying clicking Page numbers and we get records for that respective page.

There are many enumerations for PagedListRenderOptions, try different one to get different paging look and feel.

 Views: 27405 | Post Order: 106

Write for us

Hosting Recommendations