Implement Paging in Asp.net MVC (using PagedList)

Apply paging on records in asp.net MVC

Create a new project in visual studio with Asp.net 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<MultipleFileUploads.Database.author>
@using PagedList.Mvc;
@{
    ViewBag.Title = "ShowAllAuthors";
}
<link href="~/Content/PagedList.css" rel="stylesheet" />
<div class="col-lg-12">
    <table class="table-bordered">
        <thead>
            <tr>
                <th>Author last name</th>
                <th>Author first name</th>
                <th>City</th>
                <th>contract</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model)
            {
                <tr>
                    <td>@item.au_lname</td>
                    <td>@item.au_fname</td>
                    <td>@item.city</td>
                    <td>@item.contract</td>
                </tr>
            }
        </tbody>
    </table>
    Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount

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