MVC C# List with paging

Updated on     Kisan Patel

In ASP.NET MVC, paging can be done in simple way using PagedList.Mvc nuget package.

So first you need to add PagedList.Mvc nuget package using Package Manager Console. In Package Manager Console write “Install-Package PagedList.Mvc”. This will add the PagedList library for you in references.

Use Namespace – using PagedList;

Then in your controller if you are using Index ActionResult for list then in add this thing to your code

public ViewResult Index( int? page)
{
    var events = from s in db.Events
    select s;
    int pageSize = 3; // it will show three result in page
    int pageNumber = (page ?? 1);
    return View(event.OrderBy(x=>x.Id).ToPagedList(pageNumber, pageSize));
}

Now your controller is ready to do paging

So now in view page do this changes

@model PagedList.IPagedList
@using PagedList.Mvc;
@{
   ViewBag.Title = "Index";
   Layout = "~/Views/Shared/_Layout.cshtml";
}
<table class="table table-bordered table-hover">
  <tbody>
      <tr>
         <th>@Html.DisplayName("Id")</th>
         <th>@Html.DisplayName("Event Name")</th>
      </tr>
      
      @foreach (var item in Model)
      {
          <tr>
             <td>@Html.DisplayFor(modelItem =&gt; item.Id)</td>
             <td>@Html.DisplayFor(modelItem =&gt; item.EventName)</td>
          </tr>
      }
     <br/>
     page @(Model.PageCount < Model.PageNumber ? 0: Model.PageNumber) of @(Model.PageCount)
     @Html.PagedListPager(Model,page=> Url.Action("Index",new {page}))

Next run your code you can see paging in your page with counts


ASP.NET MVC

Leave a Reply