How to use PagedList In asp.net MVC

PagedList.Mvc is one of many good paging and sorting packages for ASP.NET MVC, in the below simple example I'm gonna to implement it for content (posts) of a blog post, install the PagedList.Mvc via nuget and take a look at this code. This is an action which returns blog posts:

  1.        public ActionResult List(int? page)
  2.         {
  3.             var posts = _blogService.GetAllBlogPosts();
  4.             var pageNumber = page ?? 1;
  5.             var onePageOfPosts = posts.ToPagedList(pageNumber, 10);
  6.             ViewBag.OnePageOfPosts = onePageOfPosts;
  7.             return View(posts);
  8.         }

 I just defined the OnePageOfPosts  ViewBag and onePageOfPosts.  now in the view you have to add a line of code:

  1. @using PagedList
  2. @using PagedList.Mvc;
  3. @model IEnumerable<BlogViewModel>
  4. @{
  5.       ViewBag.Title = "List";
  6.    }
  7. @foreach (var item in Model)
  8.  {
  9.            @Html.ActionLink(item.Title, "Post", "Blog", new { postId = item.PostId, urlSlug = item.UrlSlug }, null)
  10.            @Html.DisplayTextFor(blog => item.Body)
  11.   }
  12.  
  13. @Html.PagedListPager((IPagedList)ViewBag.OnePageOfPosts, page => Url.Action("List", new { page }) )

 

if you run this piece of code, you shoud have somthing like this in the output:

 

<< First < Previous 1 2 3 4 5 … Next > Last >> 

 


Tags: C# Asp.Net MVC


comments powered by Disqus