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:


4 comments:

  1. Instead of adding the PagedList NuGet package add the PagedList.mvc NuGet package (which, in turn, will pull in the PagedList package as well). Then use the Html.PagedListPager so all the work starting at 3:40 and onwards is completely unnessecary.

    Simply read the documentation and have a look at the example at https://github.com/TroyGoode/PagedList#example

    ReplyDelete
  2. Thanks for the well put together tutorial!

    ReplyDelete
  3. There are many posts on the subject, but this one definitely tops the list. thank you sir for great work!

    ReplyDelete
  4. thank you, worked sucessfully

    ReplyDelete