Learn how to create Paging feature in ASP.NET MVC

Learn how to create Paging feature in ASP.NET MVC

In ASP.NET MVC you can create paging Links very easily using 2 classes – PagingHelper.cs and PagingInfo.cs.

PagingHelper.cs
public static class PagingHelper
{
    public static MvcHtmlString PageLinks(this HtmlHelper html, PagingInfo pagingInfo, Func<int, string> pageUrl)
    {
        StringBuilder result = new StringBuilder();
        string anchorInnerHtml = "";
        for (int i = 1; i <= pagingInfo.TotalPages; i++)
        {
            TagBuilder tag = new TagBuilder("a");
            anchorInnerHtml = AnchorInnerHtml(i, pagingInfo);
 
            if (anchorInnerHtml == "..")
                tag.MergeAttribute("href", "#");
            else
                tag.MergeAttribute("href", pageUrl(i));
            tag.InnerHtml = anchorInnerHtml;
            if (i == pagingInfo.CurrentPage)
            {
                tag.AddCssClass("active");
            }
            tag.AddCssClass("paging");
            if (anchorInnerHtml != "")
                result.Append(tag.ToString());
        }
        return MvcHtmlString.Create(result.ToString());
    }
 
    public static string AnchorInnerHtml(int i, PagingInfo pagingInfo)
    {
        string anchorInnerHtml = "";
        if (pagingInfo.TotalPages <= 10)
            anchorInnerHtml = i.ToString();
        else
        {
            if (pagingInfo.CurrentPage <= 5)
            {
                if ((i <= 8) || (i == pagingInfo.TotalPages))
                    anchorInnerHtml = i.ToString();
                else if (i == pagingInfo.TotalPages - 1)
                    anchorInnerHtml = "..";
            }
            else if ((pagingInfo.CurrentPage > 5) && (pagingInfo.TotalPages - pagingInfo.CurrentPage >= 5))
            {
                if ((i == 1) || (i == pagingInfo.TotalPages) || ((pagingInfo.CurrentPage - i >= -3) && (pagingInfo.CurrentPage - i <= 3)))
                    anchorInnerHtml = i.ToString();
                else if ((i == pagingInfo.CurrentPage - 4) || (i == pagingInfo.CurrentPage + 4))
                    anchorInnerHtml = "..";
            }
            else if (pagingInfo.TotalPages - pagingInfo.CurrentPage < 5)
            {
                if ((i == 1) || (pagingInfo.TotalPages - i <= 7))
                    anchorInnerHtml = i.ToString();
                else if (pagingInfo.TotalPages - i == 8)
                    anchorInnerHtml = "..";
            }
        }
        return anchorInnerHtml;
    }
}
PagingInfo.cs
public class PagingInfo
{
    public int TotalItems { get; set; }
    public int ItemsPerPage { get; set; }
    public int CurrentPage { get; set; }
    public int TotalPages
    {
        get
        {
            return (int)Math.Ceiling((decimal)TotalItems /
                ItemsPerPage);
        }
    }
}

Explanation: The PagingHelper class will be called from the View, and it makes the Paging Links in the View. The PagingInfo Class contains the information – like total Item, Items per page, current page and total Pages.

Example – Paging Links in MVC Project

Let us now use these 2 classes to create our paging links. Add these 2 classes in your MVC Project. I prefer putting them in a new folder called Class but you can put them in any folder of your choice

Controller Code

Create a Controller and name it PagingLinks. Add the below code to it:

public ActionResult Index(int? page)
{
    CreatePagingLinks(Convert.ToInt32(page));
    return View();
}
 
public void CreatePagingLinks(int page)
{
    PagingInfo pagingInfo = new PagingInfo();
    pagingInfo.CurrentPage = page == 0 ? 1 : page;
    pagingInfo.TotalItems = 1000;
    pagingInfo.ItemsPerPage = 10;
    ViewBag.Paging = pagingInfo;
} 

Explanation: In the Index Action, I am calling the function called CreatePagingLinks(). This function creates an object of PagingInfo class and then assigns the ‘CurrentPage, TotalItems, ItemsPerPage’ to it. Here I want to create 1000 pages with each of them containing 10 records.

Finally storing this information in ViewBag.Paging variable. I will extract this variable’s value in the View.

View Code

Now go to the Index view and add this code:

<div class="pagingDiv">
    @Html.PageLinks((PagingInfo)ViewBag.Paging, x => Url.Action("Index", "PagingLinks", new { page = x }))
</div>

Explanation: I am calling the PagingHelper class’s PageLinks() function. It is provided with PagingInfo data from ViewBag.Paging variable, and the ‘URL’ of the page.

RouteConfig Code

I want my paging links to be SEO friendly. They should be like:

  • http://localhost:45505/PagingLinks
  • http://localhost:45505/PagingLinks/2
  • http://localhost:45505/PagingLinks/100

I have to make proper routes for them. So in the RouteConfig.cs file, add the below 3 routes:

routes.MapRoute("PagingPageOne", "PagingLinks", new { controller = "PagingLinks", action = "Index", page = 1 });
 
routes.MapRoute(
    name: "Paging",
    url: "PagingLinks/{page}/",
    defaults: new { controller = "PagingLinks", action = "Index", page = "" },
    constraints: new { page = @"^[0-9]+$" }
);
 
routes.MapRoute(
     name: "Default",
     url: "{controller}/{action}/{id}",
     defaults: new { controller = "PagingLinks", action = "Index", id = UrlParameter.Optional }
);

Explanation: The first route is for the URL when Page value is 1. This will create the URL like – http://localhost:45505/PagingLinks.

The second route is for the creating URL’s like – http://localhost:45505/PagingLinks/2 & http://localhost:45505/PagingLinks/100.

The third route is for setting the controller called PagingLinks Index action as the starting page of the project.

CSS Code

Add the below CSS for styling the paging links.

<style>
    .pagingDiv {
        background: #f2f2f2;
    }
 
        .pagingDiv > a {
            display: inline-block;
            padding: 0px 9px;
            margin-right: 4px;
            border-radius: 3px;
            border: solid 1px #c0c0c0;
            background: #e9e9e9;
            box-shadow: inset 0px 1px 0px rgba(255,255,255, .8), 0px 1px 3px rgba(0,0,0, .1);
            font-size: .875em;
            font-weight: bold;
            text-decoration: none;
            color: #717171;
            text-shadow: 0px 1px 0px rgba(255,255,255, 1);
        }
 
            .pagingDiv > a:hover {
                background: #fefefe;
                background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#FEFEFE), to(#f0f0f0));
                background: -moz-linear-gradient(0% 0% 270deg,#FEFEFE, #f0f0f0);
            }
 
            .pagingDiv > a.active {
                border: none;
                background: #616161;
                box-shadow: inset 0px 0px 8px rgba(0,0,0, .5), 0px 1px 0px rgba(255,255,255, .8);
                color: #f0f0f0;
                text-shadow: 0px 0px 3px rgba(0,0,0, .5);
            }
</style>
paging links image

Once you run the application this is how the paging Links will look. Check the download link:

DOWNLOAD

I have written 2 very useful tutorial on Validation in ASP.NET MVC. You should check them:
1. Server Side Validation in ASP.NET Core
2. Client Side Validation in ASP.NET Core

SHARE THIS ARTICLE

  • linkedin
  • reddit
yogihosting

ABOUT THE AUTHOR

I hope you enjoyed reading this tutorial. If it helped you then consider buying a cup of coffee for me. This will help me in writing more such good tutorials for the readers. Thank you. Buy Me A Coffee donate