Implement Paging in MVC (using PagedList)

Apply paging on records in MVC

Create a new project in visual studio with MVC template. Go to tools and Library package manger->package manger console and write following command Install-Package PagedList.Mvc. it will install a very help full extension which help us implementing paging. After that click on controller and add a new controller name it ShowAllAuthors. i am using Pubs database with entity framework database first approach. You can learn more about How we connect database using database first approach in entity framework

ShowAllAuthors Code

First we need to add reference PagedList in our controller

using PagedList;
 public ActionResult ShowAllAuthors(int? page)
            int pageNo = (page ?? 1);
            int PerPageSize=5;
            pubsEntities dbcontext=new pubsEntities();
            return View(dbcontext.authors.OrderBy(i=>i.au_lname).ToPagedList(pageNo,PerPageSize));

Now add ShowAllAuthors view

@model PagedList.IPagedList<>
@using PagedList.Mvc;
    ViewBag.Title = "ShowAllAuthors";
<link href="~/Content/PagedList.css" rel="stylesheet" />
<div class="col-lg-12">
    <table class="table-bordered">
                <th>Author last name</th>
                <th>Author first name</th>
            @foreach (var item in Model)
    Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount

    @Html.PagedListPager(Model, page => Url.Action("ShowAllAuthors",
    new { page }))