Skip to content

Instantly share code, notes, and snippets.

@jarrettmeyer
Created May 29, 2012 17:20
Show Gist options
  • Select an option

  • Save jarrettmeyer/2829612 to your computer and use it in GitHub Desktop.

Select an option

Save jarrettmeyer/2829612 to your computer and use it in GitHub Desktop.
Simple Pagination with MVC3 + Twitter Bootstrap
@model IPaginate
<div class="pagination pagination-centered">
<ul>
@for (int i = 1; i <= Model.PageCount; i += 1)
{
string cls = "";
if (i == Model.Page)
{
cls += " active";
}
<li class="@cls"><a href="@GetPagedUrl(i)">@i</a></li>
}
</ul>
</div>
@functions
{
private bool HasPageInQuery
{
get
{
var url = Request.Url;
if (url == null)
return false;
var query = url.Query;
return System.Text.RegularExpressions.Regex.IsMatch(query, @"[?&]Page=\d+");
}
}
private bool HasQuery
{
get
{
var url = Request.Url;
if (url == null)
return false;
return !string.IsNullOrEmpty(url.Query);
}
}
private string GetPagedUrl(int page)
{
var pageQuery = string.Format("Page={0}", page);
if (HasPageInQuery)
return System.Text.RegularExpressions.Regex.Replace(Request.Url.Query, @"Page=\d+", pageQuery);
if (HasQuery)
return Request.Url + "&" + pageQuery;
return Request.Url + "?" + pageQuery;
}
}
/// <summary>
/// Indicates that a model provides support for pagination.
/// See http://twitter.github.com/bootstrap/components.html#pagination.
/// </summary>
public interface IPaginate
{
/// <summary>
/// Gets the current page in the record set.
/// </summary>
int Page { get; }
/// <summary>
/// Gets the total number of pages in the record set.
/// </summary>
int PageCount { get; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment