Filter posts by the Tags of Blog section!

How to use PagedList In MVC Friday, 20 September 2013

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:


       public ActionResult List(int? page)
            var posts = _blogService.GetAllBlogPosts();
            var pageNumber = page ?? 1;
            var onePageOfPosts = posts.ToPagedList(pageNumber, 10);
            ViewBag.OnePageOfPosts = onePageOfPosts;
            return View(posts);


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


@using PagedList
@using PagedList.Mvc;
@model IEnumerable<BlogViewModel>
      ViewBag.Title = "List";
@foreach (var item in Model)
           @Html.ActionLink(item.Title, "Post", "Blog", new { postId = item.PostId, urlSlug = item.UrlSlug }, null)
           @Html.DisplayTextFor(blog => item.Body)

@Html.PagedListPager((IPagedList)ViewBag.OnePageOfPosts, page => Url.Action("List", new { page }) )


if you run this piece of code, you should have something like this in the output:


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


comments powered by Disqus