So I am building my own custom blog using the ASP.NET MVC Framework, and I have been working on the paging aspect. I will be going into more detail how i achieved this but for now, I am publishing a HtmlHelper I have made which has helped me, believe it or not lol, in the paging. The way I have designed it also is kind of decoupled, so i see no reason for its integration into many other applications.
My implmentation of the HtmlHelper is here:
<%= Html.Pager((pc.StartingIndex / pc.PageSize) ,pc.PageSize,pc.TotalRecords,"/Home/Page") %>
And the code which makes it is here. The major thing is calculating the seed of the iteration based on the current page, after that you are laughing!
public static string Pager(this HtmlHelper helper, int currentPage, int currentPageSize, int totalRecords, string urlPrefix)
{
StringBuilder sb1 = new StringBuilder();
int seed = currentPage % currentPageSize == 0 ? currentPage : currentPage - (currentPage % currentPageSize);
if(currentPage > 0)
sb1.AppendLine(String.Format("<a href=\"{0}/{1}\">Previous</a>", urlPrefix, currentPage));
if(currentPage - currentPageSize >= 0)
sb1.AppendLine(String.Format("<a href=\"{0}/{1}\">...</a>", urlPrefix, (currentPage - currentPageSize) + 1));
for (int i = seed; i < Math.Round((totalRecords / 10) + 0.5) && i < seed + currentPageSize; i++)
{
sb1.AppendLine(String.Format("<a href=\"{0}/{1}\">{1}</a>", urlPrefix, i + 1));
}
if (currentPage + currentPageSize <= (Math.Round((totalRecords / 10) + 0.5) - 1))
sb1.AppendLine(String.Format("<a href=\"{0}/{1}\">...</a>", urlPrefix, (currentPage + currentPageSize) + 1));
if (currentPage < (Math.Round((totalRecords / 10) + 0.5) - 1))
sb1.AppendLine(String.Format("<a href=\"{0}/{1}\">Next</a>", urlPrefix, currentPage + 2));
return sb1.ToString();
}
Hope this helps some people,
Cheers,
Andrew :-)