Last active
December 26, 2015 16:59
-
-
Save markis/7183986 to your computer and use it in GitHub Desktop.
This file contains 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
public static class ExtensionMethods | |
{ | |
/// <summary> | |
/// Creates paginated links | |
/// </summary> | |
/// <param name="helper">HtmlHelper class that can provide access to helpful functionality</param> | |
/// <param name="startPage">Starting page (most likely 1)</param> | |
/// <param name="currentPage">Number of the current page</param> | |
/// <param name="totalPages">Number of total pages</param> | |
/// <param name="pagesToShow">Number of pages to show forward and backward</param> | |
/// <param name="currentPageUrlParameter">URL Parameter that sets the current page</param> | |
public static MvcHtmlString Pager(this HtmlHelper helper, int startPage, int currentPage, int totalPages, int pagesToShow, string currentPageUrlParameter) | |
{ | |
System.Web.Routing.RouteData routeData = helper.ViewContext.RouteData; | |
string actionName = routeData.GetRequiredString("action"); | |
string controller = routeData.GetRequiredString("controller"); | |
System.Web.Routing.RouteValueDictionary values = routeData.Values; | |
if (!values.ContainsKey(currentPageUrlParameter)) | |
values.Add(currentPageUrlParameter, currentPage); | |
bool started = false; | |
StringBuilder html = Enumerable.Range(startPage, totalPages) /* Create a list from the first page to the last page */ | |
.Where(i => (currentPage - pagesToShow) < i & i < (currentPage + pagesToShow)) /* filter the list to just the pages we want to show */ | |
.Aggregate(new StringBuilder(@"<div class=""pager"">"), (seed, page) => | |
{ | |
/* run through the list of pages and create the string of page numbers */ | |
values["page"] = page; | |
string style = "pagerPage"; | |
if (page == startPage) | |
style += " firstPage"; | |
if (page == totalPages) | |
style += " lastPage"; | |
var htmlDic = new Dictionary<string, object>(); | |
htmlDic.Add("style", style); | |
if (started) | |
seed.Append(" | "); | |
else | |
started = true; | |
if (page == currentPage) | |
seed.AppendFormat("<span style="pagerPage currentPage">{0}</span>", page); | |
else | |
seed.Append(helper.ActionLink(page.ToString(), actionName, controller, values, htmlDic).ToHtmlString()); | |
return seed; | |
}); | |
html.Append(@"</div>"); | |
return MvcHtmlString.Create(html.ToString()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment