Ehsan Ghanbari

Experience, DotNet, Solutions

How to use PagedList In MVC

PagedList.Mvc is one of many good paging and sorting packages for ASP.NET MVC, in the below simple example I'm gonna 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.   }
  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 >> 


About Me

Ehsan Ghanbari

Hi! my name is Ehsan. I'm a developer, passionate technologist, and fan of clean code. I'm interested in enterprise and large-scale applications architecture and design patterns. I spend a lot of time on software architecture. Since 2008, I've been as a developer for different companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the past years, Read More

Post Tags
Pending Blog Posts
using Elmah in MVC4
Using FluentSecurity in MVC
Strategic design
Factory Pattern
time out pattern in ajax
Redis as a cache server
How to use PagedList In MVC
Multiple submit buttons in MVC
Domain driven design VS model driven architecture
What's the DDD-lite?
comments powered by Disqus