A simple Bootstrap Pager Html Helper
Introduction:
In ASP.NET MVC 5, MVC project templates uses Bootstrap 3.0 user interface framework. It makes the user interface sleek and responsive look. Bootstrap 3.0 also have nice pagination support. In this article, I will show you how to create a simple html helper which will generate Bootstrap 3.0 pagination specific markup.
Description:
So, what do we need in this pager html helper? currentPageIndex(the current page number), action(the url pointing to an action), totalItems(total number(count) of items), pageSize(items per page) and numberOfLinks(number of links in a page, for example if numberOfLinks = 5 then it will generate 1 2 3 4 5)
namespace Shopex.Web.HtmlHelpers { public static class HtmlHelperExtensions { public static MvcHtmlString BootstrapPager(this HtmlHelper helper, int currentPageIndex, Func<int, string> action, int totalItems, int pageSize = 10, int numberOfLinks = 5) { if (totalItems <= 0) { return MvcHtmlString.Empty; } var totalPages = (int)Math.Ceiling(totalItems / (double)pageSize); var lastPageNumber = (int)Math.Ceiling((double)currentPageIndex / numberOfLinks) * numberOfLinks; var firstPageNumber = lastPageNumber - (numberOfLinks - 1); var hasPreviousPage = currentPageIndex > 1; var hasNextPage = currentPageIndex < totalPages; if (lastPageNumber > totalPages) { lastPageNumber = totalPages; } var ul = new TagBuilder("ul"); ul.AddCssClass("pagination"); ul.InnerHtml += AddLink(1, action, currentPageIndex == 1, "disabled", "<<", "First Page"); ul.InnerHtml += AddLink(currentPageIndex - 1, action, !hasPreviousPage, "disabled", "<", "Previous Page"); for (int i = firstPageNumber; i <= lastPageNumber; i++) { ul.InnerHtml += AddLink(i, action, i == currentPageIndex, "active", i.ToString(), i.ToString()); } ul.InnerHtml += AddLink(currentPageIndex + 1, action, !hasNextPage, "disabled", ">", "Next Page"); ul.InnerHtml += AddLink(totalPages, action, currentPageIndex == totalPages, "disabled", ">>", "Last Page"); return MvcHtmlString.Create(ul.ToString()); } private static TagBuilder AddLink(int index, Func<int, string> action, bool condition, string classToAdd, string linkText, string tooltip) { var li = new TagBuilder("li"); li.MergeAttribute("title", tooltip); if (condition) { li.AddCssClass(classToAdd); } var a = new TagBuilder("a"); a.MergeAttribute("href", !condition ? action(index) : "javascript:"); a.SetInnerText(linkText); li.InnerHtml = a.ToString(); return li; } } }
Now you can use this html helper in your view,
@using HtmlHelpers @Html.BootstrapPager(pageIndex, index => Url.Action("Index", "Product", new { pageIndex = index }), Model.TotalCount, numberOfLinks: 10)
Summary:
Most applications requires some sort of nice and clean pagination. Bootstrap 3.0 have nice pagination support. In this article, I showed you how to create a simple html helper which generate Bootstrap 3.0 pagination specific markup.