Set Paging Size In ASP.NET MVC

This article is an answer to the following searches.

  • Set Paging Size in ASP.NET MVC 
  • Pagination in ASP.NET MVC
  • ASP.NET MVC Paged list Page Size Dropdown List
  • How to set Page Size inASP.NET MVC?
  • How to assign page size dynamically by ASP.NET MVC?

In this article, you will come to know how to set the paging size in ASP.NET MVC.

Many times, our INDEX page has several records, say, greater than 50 records. If you do not do paging, all 50 records will come at one time. For a user to view all the 50 records, they will have to go through scrolling down and down. With the help of paging, you can set the limit to display the total number of records at a time.

Example

ScenarioSr. No.Total RecordsPaging Size(To display nos. of records in one page)Total Pages
150 records510 Page Nos.(1,2,3,4,5,6,7,8,9,10)
250 records105 Page Nos. (1,2,3,4,5)
350 records154 Page Nos.(1,2,3,4) (4 pages because within 3 pages it will cover 45 records rest 5 records goes to page no. 4)

In the third scenario, you see that 50 records take four paging, which means

1st page          = 01 - 15 records

2nd page         = 16 - 30 records

3rd page         = 31 - 45 records

4th page          = 46 - 50 records

You will come to know about more in step by step implementation section.

Benefits of Pagination in Web Application

  1. Reduce pressure on the server - Server easily processes the small chunks of records and back to the user.
  2. Fast page processing - Page load will be faster.

What is PagedList.MVC?

An HtmlHelper method generates the paging control with the use of PagedList Library. With the help of IEnumerable(T), you can create pagination but you have to define the page size.

For more detail related to PagedList.MVC, plesae visit following link.

  • https://www.nuget.org/packages/PagedList.Mvc/4.5.0#
  • https://www.nuget.org/packages/PagedList/

Step by step implementation

In this section, you will see step by step implementation. I will suggest you follow the same steps at your end to learn perfectly.

STEP 1 - Table Sturcture and Creation

Before you start working on Visual Studio, first, create a table and fill it with some records (around 20 or more).

  1. SET ANSI_NULLS ON  
  2. GO  
  3.   
  4. SET QUOTED_IDENTIFIER ON  
  5. GO  
  6.   
  7. CREATE TABLE [dbo].[tblInvoices](  
  8.     [InvoiceID] [int] IDENTITY(1,1) NOT NULL,  
  9.     [InvoiceDate] [datetime] NULL,  
  10.     [ClientName] [nvarchar](50) NULL,  
  11.     [ClientZone] [nvarchar](50) NULL,  
  12.     [InvoiceAmount] [intNULL,  
  13.  CONSTRAINT [PK_tblInvoices] PRIMARY KEY CLUSTERED   
  14. (  
  15.     [InvoiceID] ASC  
  16. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  17. ON [PRIMARY]  
  18.   
  19. GO  

STEP 2

Create a new project called “SetPagingSite”.

Pagination in Asp.Net MVC

After pressing OK button, select the blue color bordered options. Select MVC option and click on "Change Authentication" button. Then, change to No authentication.

Pagination in Asp.Net MVC
Pagination in Asp.Net MVC

STEP 3

Select Solution Explorer and right-click on the project name, select Add --> New Item.

Or

Simply press CTRL + SHIFT + A  to insert a new item called ADO.NET Entity Data Model.

Pagination in Asp.Net MVC

Select ADO.NET Entity Data Model item and name it as “InvoiceModel”.

Pagination in Asp.Net MVC

Select "Code First from database".

Pagination in Asp.Net MVC

Pagination in Asp.Net MVC

After your database is connected, select "tblInvoices".

Pagination in Asp.Net MVC

After inserting ADO.NET Entity Data Model called “InvoiceModel”, you can see the followig changes into your project.

Two files are added -

  1. cs - Model File.
  2. cs - DbContext Class

Web.Config file and Reference are updated with Entity Framework and Connection Strings.

After the above activities get completed, now we go for inserting PagedList.MVC into project through NuGet.

STEP  4

Select Solution Explorer, right-click on the project name, and select "Manage NuGet Packages".

Pagination in Asp.Net MVC

Select PagedList.MVC as shown in the image. You can see a short description of PagedList.MVC which bordered in blue.

Pagination in Asp.Net MVC

Click on "Install" button to install PagedList.MVC NuGet package. As we click on "Install", the following dialog box will appear. Select OK to install.

Pagination in Asp.Net MVC

In output window, you can see the following messages.

Pagination in Asp.Net MVC

STEP  5

Now, let us work on Controller. By default, we got Home Controller which is in the Controllers folder.

Double click on Home Controller.

Pagination in Asp.Net MVC

Now, insert a new method called InvoiceList.

  1. public ActionResult InvoiceList()  
  2.        {  
  3.            return View();  
  4.        }  

Right-click on InvoiceList method and select Add View… option.

Pagination in Asp.Net MVC

Please build the solution here before going to create Add View…

As you click on Add View… option, select the following value as per Add View dialog box.

Pagination in Asp.Net MVC

STEP  6

Now, change the default action method to execute. Switch to Solution Explorer, click on “App_Start” folder, and double click on file named ”RouteConfig.cs” to change the default method to execute. By default, Home controller’s Index Action Method is executing. Now, let us change the Action Method to “InvoiceList”. That's all.

After changing RouteConfig.cs, our file looks like this.

Code in RouteConfig.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using System.Web.Routing;  
  7.   
  8. namespace SetPagingSize  
  9. {  
  10.     public class RouteConfig  
  11.     {  
  12.         public static void RegisterRoutes(RouteCollection routes)  
  13.         {  
  14.             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  15.   
  16.             routes.MapRoute(  
  17.                 name: "Default",  
  18.                 url: "{controller}/{action}/{id}",  
  19.                 defaults: new { controller = "Home", action = "InvoiceList", id = UrlParameter.Optional }  
  20.             );  
  21.         }  
  22.     }  
  23. }  

STEP 7 

Write the Controller Action Method and update the generated View. Use Namespace in HomeController.cs using PagedList;

Now, let us write the code for our Home Controller’s InvoiceList method.

InvoiceList Action Method

  1. //To return all Invoice List as per Page number and Page Size  
  2.      public ActionResult InvoiceList(int? page, int? pageSize)  
  3.      {  
  4.          
  5.          int pageIndex = 1;  
  6.          pageIndex = page.HasValue ? Convert.ToInt32(page) : 1;  
  7.   
  8.            
  9.          //Ddefault size is 5 otherwise take pageSize value  
  10.          int defaSize = (pageSize ?? 5);  
  11.   
  12.          ViewBag.psize = defaSize;  
  13.   
  14.          //Dropdownlist code for PageSize selection  
  15.          //In View Attach this  
  16.          ViewBag.PageSize = new List<SelectListItem>()  
  17.          {  
  18.              new SelectListItem() { Value="5", Text= "5" },  
  19.              new SelectListItem() { Value="10", Text= "10" },  
  20.              new SelectListItem() { Value="15", Text= "15" },  
  21.              new SelectListItem() { Value="25", Text= "25" },  
  22.              new SelectListItem() { Value="50", Text= "50" },  
  23.          };  
  24.   
  25.          //Create a instance of our DataContext  
  26.          InvoiceModel _dbContext = new InvoiceModel();  
  27.   
  28.   
  29.          IPagedList<tblInvoice> involst = null;  
  30.   
  31.          //Alloting nos. of records as per pagesize and page index.  
  32.          involst = _dbContext.tblInvoices.OrderBy(x => x.InvoiceID).ToPagedList(pageIndex, defaSize);  
  33.   
  34.          return View(involst);  
  35.      }  

Now, click on the View folder and select InvoiceList.cshtml file which we had created in STEP 5.

Now, let us modify InvoiceList.cshtml as per our requirement. Please understand the changed code which is marked in bold letters and font size is slightly bigger.

CODE in InvoiceList.html  (with comments)

  1. @model PagedList.IPagedList <SetPagingSize.tblInvoice>  
  2. @using PagedList.Mvc;    
  3. @{  
  4.     ViewBag.Title = "InvoiceList";  
  5. }  
  6.   
  7. <h2>InvoiceList</h2>  
  8.   
  9. <p>  
  10.     @Html.ActionLink("Create New""Create")  
  11. </p>  
  12. @*Html.BeginForm run the HOME controller InvoiceList Action's GET method when form get submitted.*@  
  13. @using (Html.BeginForm("InvoiceList""Home", FormMethod.Get, new { id = "form1" }))  
  14.   
  15. {  
  16. <div id='Paging' style="text-align: center">  
  17.  @*Dorpdownlist generation code*@  
  18.     Page Size: @Html.DropDownList("pageSize")  
  19.       
  20. <br />(Nos. of Records To Display)  
  21.     <br />  
  22.     <br />  
  23.     Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber)  
  24.     of @Model.PageCount  
  25.       
  26.     @Html.PagedListPager(Model, page => Url.Action("InvoiceList"new { page, pageSize = ViewBag.psize }))  
  27. </div>  
  28. }  
  29. <table class="table">  
  30.     <tr>  
  31.         <th>  
  32.             Invoice No.  
  33.         </th>  
  34.         <th>  
  35.             Invoice Date  
  36.         </th>  
  37.         <th>  
  38.             Client Name  
  39.         </th>  
  40.         <th>  
  41.             Client Zone  
  42.         </th>  
  43.         <th>  
  44.             Invoice Amount  
  45.         </th>  
  46.         <th></th>  
  47.     </tr>  
  48.   
  49. @foreach (var item in Model)  
  50. {  
  51.     <tr>  
  52.         <td>  
  53.             @Html.DisplayFor(modelItem => item.InvoiceID)  
  54.         </td>  
  55.         <td>  
  56.             @Html.DisplayFor(modelItem => item.InvoiceDate)  
  57.         </td>  
  58.         <td>  
  59.             @Html.DisplayFor(modelItem => item.ClientName)  
  60.         </td>  
  61.         <td>  
  62.             @Html.DisplayFor(modelItem => item.ClientZone)  
  63.         </td>  
  64.         <td>  
  65.             @Html.DisplayFor(modelItem => item.InvoiceAmount)  
  66.         </td>  
  67.         <td>  
  68.             @Html.ActionLink("Edit""Edit"new { id = item.InvoiceID }) |  
  69.             @Html.ActionLink("Details""Details"new { id = item.InvoiceID }) |  
  70.             @Html.ActionLink("Delete""Delete"new { id = item.InvoiceID })  
  71.         </td>  
  72.     </tr>  
  73. }  
  74.       
  75. </table>  
  76. <script type="text/javascript">  
  77.     $(function () {  
  78.         $("#pageSize").change(function () {  
  79.             alert("abc");  
  80.             $("#form1").submit();  
  81.         });  
  82.     });  
  83. </script>  

Now, update the _Layout.cshtml with 1 change. The following text located at bottom of the file is moved into head section.

  1. @Scripts.Render("~/bundles/jquery")  
  2.     @Scripts.Render("~/bundles/bootstrap")  
  3.     @RenderSection("scripts", required: false)  

Changed code is marked in bold letters and font size is slightly bigger.

CODE in _Layout.cshtml

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <meta charset="utf-8" />  
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">  
  6.     <title>@ViewBag.Title - My ASP.NET Application</title>  
  7.     @Styles.Render("~/Content/css")  
  8.     @Scripts.Render("~/bundles/modernizr")  
  9.   
  10.     @Scripts.Render("~/bundles/jquery")  
  11.     @Scripts.Render("~/bundles/bootstrap")  
  12.     @RenderSection("scripts", required: false)  
  13. </head>  
  14. <body>  
  15.     <div class="navbar navbar-inverse navbar-fixed-top">  
  16.         <div class="container">  
  17.             <div class="navbar-header">  
  18.                 <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">  
  19.                     <span class="icon-bar"></span>  
  20.                     <span class="icon-bar"></span>  
  21.                     <span class="icon-bar"></span>  
  22.                 </button>  
  23.                 @Html.ActionLink("Application name""Index""Home"new { area = "" }, new { @class = "navbar-brand" })  
  24.             </div>  
  25.             <div class="navbar-collapse collapse">  
  26.                 <ul class="nav navbar-nav">  
  27.                     <li>@Html.ActionLink("Home""Index""Home")</li>  
  28.                     <li>@Html.ActionLink("About""About""Home")</li>  
  29.                     <li>@Html.ActionLink("Contact""Contact""Home")</li>  
  30.                 </ul>  
  31.             </div>  
  32.         </div>  
  33.     </div>  
  34.     <div class="container body-content">  
  35.         @RenderBody()  
  36.         <hr />  
  37.         <footer>  
  38.             <p>© @DateTime.Now.Year - My ASP.NET Application</p>  
  39.         </footer>  
  40.     </div>  
  41.   
  42. </body>  
  43. </html>  

Press F5 to view the Invoice List output.

Output

Pagination in Asp.Net MVC

On the next screen, I have changed the page size 5 to 15 rows.
Pagination in Asp.Net MVC

Happy Coding..

Up Next
    Ebook Download
    View all
    Learn
    View all