Created
May 15, 2017 12:53
-
-
Save deepumi/678c743bc033dfde8f85f89c25375a01 to your computer and use it in GitHub Desktop.
MVC Pagination helper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //orignal post - http://joelabrahamsson.com/twitter-style-paging-with-aspnet-mvc-and-jquery/ | |
| public static class PagerHelper | |
| { | |
| public static MvcHtmlString BootstrapPager(this HtmlHelper helper, int currentPageIndex, 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 TagBuilderExtension("ul"); | |
| ul.AddCssClass("pagination"); | |
| ul.Append(AddLink(1, currentPageIndex == 1, "disabled", "<<", "First Page")); | |
| ul.Append(AddLink(currentPageIndex - 1, !hasPreviousPage, "disabled", "<", "Previous Page")); | |
| for (var i = firstPageNumber; i <= lastPageNumber; i++) | |
| ul.Append(AddLink(i, i == currentPageIndex, "active", i.ToString(), i.ToString())); | |
| ul.Append(AddLink(currentPageIndex + 1, !hasNextPage, "disabled", ">", "Next Page")); | |
| ul.Append(AddLink(totalPages, currentPageIndex == totalPages, "disabled", ">>", "Last Page")); | |
| return MvcHtmlString.Create(ul.ToString()); | |
| } | |
| private static TagBuilder AddLink(int index, 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 ? "javascript:getpage('" + index + "')" : "javascript:"); | |
| a.SetInnerText(linkText); | |
| li.InnerHtml = a.ToString(); | |
| return li; | |
| } | |
| } | |
| public class TagBuilderExtension : TagBuilder | |
| { | |
| private readonly StringBuilder sb = new StringBuilder(); | |
| public TagBuilderExtension(string tagName) : base(tagName) { } | |
| public void Append(TagBuilder tb) => sb.Append(tb); | |
| public override string ToString() | |
| { | |
| InnerHtml = sb.ToString(); | |
| return base.ToString(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment