Thursday 28 March 2013

MVC 4 - How to add paging to table

Watch this example on YOUTube
Go to Tools/Libary Package Manager/Manage NuGet Packages for Solution...

Search for pagedList and install it.


 Add new controller - in my case it will point to StyleMaster table in my database - I am using EF - more info in my older post - MVC 4 - Simple CRUD example.  Once this controller is created - I will have between the others index view with table.  My next step will be to add paging functionality to that table.


In style controller add the following using
using PagedList;



then modify index method
        public ActionResult Index(int? page)
        {
            var stylemasters = db.StyleMasters.Include(s => s.GroupMaster).Include(s => s.StyleTypeMaster).OrderBy(s => s.StyleName); //ensure records are sorted.
            if (Request.HttpMethod != "GET")
            {
                page = 1;
            }
            int pageSize = 2;
            int pageNumber = (page ?? 1);
            return View(stylemasters.ToPagedList(pageNumber, pageSize));
        }

in view replace
@model IEnumerable<MvcTestingCRUD.Models.StyleMaster>
with
@model PagedList.IPagedList<MvcTestingCRUD.Models.StyleMaster>

replace code that looks like
        <th>
            @Html.DisplayNameFor(model => model.StyleId)
        </th>
with
        <th>
            @Html.DisplayNameFor(model => model.First().StyleId)
        </th>

at the end of the page after </table> add the following div

<div>
    Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount
    @if (Model.HasPreviousPage)
    {
        @Html.ActionLink("<<", "Index", new { page = 1})
        @Html.Raw(" ");
        @Html.ActionLink("< Prev", "Index", new {page = Model.PageNumber - 1})
    }
    else{
     @:<<
     @Html.Raw(" ");
        @:< Prev  
    }

    @if (Model.HasNextPage)
    {
        @Html.ActionLink("Next >", "Index", new {page = Model.PageNumber + 1})
        @Html.Raw(" ");
        @Html.ActionLink(">>", "Index", new {page = Model.PageCount})
    }
    else{
     @:Next >
     @Html.Raw(" ")
@:>>  
    }
</div>

That's it.  Now when you run your website - paging will be presented: