Thursday, 22 January 2015

Html helper extension method for creating pagination links in ASP.NET MVC

Add below Extension method to your project
using System;
using System.Web.Mvc;
using System.Text;

namespace YourWebUI.HtmlHelpers
{
    public static class PagingHelpers
    {
        public static MvcHtmlString PageLinks(this HtmlHelper html, int totalPages, Func pageUrl)
        {
            StringBuilder pageLinks = new StringBuilder();
            for (int i = 1; i <= totalPages; i++)
            {
                TagBuilder pageLink = new TagBuilder("a");
                pageLink.MergeAttribute("href", pageUrl(i));
                pageLink.InnerHtml = i.ToString();
                pageLinks.Append(pageLink.ToString());
                pageLinks.Append(i == totalPages? "" : " | ");
            }
            return MvcHtmlString.Create(pageLinks.ToString());
        }
    }
}
Add the namespace YourWebUI.HtmlHelpers to web.config
  <system.web.webPages.razor>
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        ...
        <add namespace="YourWebUI.HtmlHelpers"/>
      </namespaces>
    </pages>
  </system.web.webPages.razor>
Razor syntax for calling the method
 @Html.PageLinks(5, x => Url.Action("Index", new { page = x }))
Sample output
<a href="/?page=1">1</a> | <a href="/?page=2">2</a> | <a href="/?page=3">3</a> | <a href="/?page=4">4</a> | <a href="/?page=5">5</a>
Click Here to see a different way of doing this.

No comments:

Post a Comment