I’m using the Grid Html Helper from the MvcContrib project (www.mvccontrib.org). The default grid can create automatic pagination links at the bottom of the grid, which is a pretty nice feature. However, in order to accomodate our design, I needed some more functionality:
- I needed paging at the top of the grid too
- I needed to add some custom markup surrounding the grid to make it look right
Luckily, this wasn’t too hard. I started by creating a class that inherits from MvcContrib.UI.Html.Grid.Grid<T>. Something like this:
public class AdminMerchantGrid<T> : MvcContrib.UI.Html.Grid.Grid<T> where T : class
In order to render pagination at the top I had to override the RenderGridStart like so:
protected override void RenderGridStart()
{
MvcContrib.Pagination.IPagination items = base.Items as MvcContrib.Pagination.IPagination;
RenderPagination(items, true);
base.RenderGridStart();
}
And I overrode the RenderGridEnd too:
protected override void RenderGridEnd(bool isEmpty)
{
base.RenderText("</table>");
MvcContrib.Pagination.IPagination items = base.Items as MvcContrib.Pagination.IPagination;
this.RenderPagination(items, false);
}
Now these are using a RenderPagination method that takes into account whether the pagination is on the top or bottom in order to fit into our design. Notice how I could put in the custom CSS class names too which is kind of cool. :
protected void RenderPagination(MvcContrib.Pagination.IPagination pagedList, bool isTop)
{
StringBuilder sb = new StringBuilder();
if (!isTop)
{
sb.AppendLine("<div class=\"mainbox\">");
}
if (pagedList != null && pagedList.TotalItems > 0)
{
sb.AppendLine("<div class=\"paging\">");
sb.AppendLine("<span>");
for (int i = 1; i <= pagedList.TotalPages; i++)
{
sb.Append(this.CreatePageLink(i, i.ToString()));
if (i < pagedList.TotalPages)
sb.Append(" ");
}
sb.AppendLine("</span>");
sb.AppendLine("<span class=\"position\">");
sb.Append("Page ");
sb.Append(pagedList.PageNumber);
sb.Append(" of ");
sb.Append(pagedList.TotalPages);
if (pagedList.PageNumber > 1)
sb.Append(this.CreatePageLink(pagedList.PageNumber - 1, "<"));
else
sb.Append("<");
sb.Append(" ");
if (pagedList.PageNumber < pagedList.TotalPages)
sb.Append(this.CreatePageLink(pagedList.PageNumber + 1, ">"));
else
sb.Append(">");
sb.AppendLine("</span>");
sb.AppendLine("</div>");
sb.AppendLine("<div class=\"cl\"> </div>");
}
if (isTop)
sb.AppendLine("</div>");
if (!isTop)
sb.AppendLine("</div>");
base.RenderText(sb.ToString());
}
Boy do I love Reflector! Most of the RenderPagination method came from the original MvcContrib’s method. I just added couple things in there like if (isTop) and such. So not only is MvcContrib’s Grid a simple, easy to use solution for building a grid, it’s pretty easily extensible too!