WebGrid Custom Paging Links To Avoid Load On Server Using Stored Procedure And ASP.NET MVC

Introduction

In ASP.NET, we use GridView for fetching the data and showing the output. Also, we implement CRUD operationss using GridView. We can do the same  implementation in ASP.NET MVC using WebGrid.

Link For More References

Description

I will show you how to fetch the data dynamically from the database and bind to the WebGrid control, using the stored procedure in MVC 4.0. In this blog, today, I will show you how to write code in ASP.NET MVC for implementation of WebGrid Control using Static Data. In later sessions, I will show you the process of using GridView Dynamically, that means using the SQL Server data source.

Link To Source Code
 
 
Important Code Sections To Follow

Code ref of GridviewController.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.Data;  
  7. using SatyaWebGridCustomPagingLinks.Models;  
  8. using System.Web.Helpers;  
  9.   
  10. namespace SatyaWebGridCustomPagingLinks.Controllers  
  11. {  
  12.     public class GridviewController : Controller  
  13.     {  
  14.         //  
  15.         // GET: /Gridview/  
  16.           
  17.         public ActionResult Index(int? page)  
  18.         {  
  19.             List<modeldata> lmd = new List<modeldata>();  
  20.             //creating list of model.    
  21.   
  22.             DataSet ds = new DataSet();  
  23.   
  24.             Connection.Connection con = new Connection.Connection();  
  25.   
  26.             //The connection namespace as we mentioned earlier .    
  27.             //namespace Gridsample.Connection.    
  28.   
  29.             // connection to getdata.    
  30.   
  31.             ds = con.mydata();  
  32.   
  33.             // fill dataset    
  34.   
  35.   
  36.             foreach (DataRow dr in ds.Tables[0].Rows)  
  37.   
  38.             // loop for adding add from dataset to list<modeldata>    
  39.             {  
  40.                 lmd.Add(new modeldata  
  41.                 {  
  42.                     // adding data from dataset row in to list<modeldata>    
  43.                     SM_StudentID = Convert.ToInt64(dr["SM_StudentID"]),  
  44.                     SM_Name = dr["SM_Name"].ToString()  
  45.                 });  
  46.             }  
  47.             return View(lmd.ToList());  
  48.         }  
  49.   
  50.         public ActionResult EfficientWay()  
  51.         {  
  52.             return View();  
  53.         }  
  54.   
  55.         [HttpGet]  
  56.         public JsonResult EfficientPaging(int? page)  
  57.         {  
  58.             List<modeldata> lmd = new List<modeldata>();  
  59.             //creating list of model.    
  60.   
  61.             DataSet ds = new DataSet();  
  62.   
  63.             Connection.Connection con = new Connection.Connection();  
  64.   
  65.             //The connection namespace as we mentioned earlier .    
  66.             //namespace Gridsample.Connection.    
  67.   
  68.             // connection to getdata.    
  69.   
  70.             ds = con.mydata();  
  71.   
  72.             // fill dataset    
  73.   
  74.   
  75.             foreach (DataRow dr in ds.Tables[0].Rows)  
  76.   
  77.             // loop for adding add from dataset to list<modeldata>    
  78.             {  
  79.                 lmd.Add(new modeldata  
  80.                 {  
  81.                     // adding data from dataset row in to list<modeldata>    
  82.                     SM_StudentID = Convert.ToInt64(dr["SM_StudentID"]),  
  83.                     SM_Name = dr["SM_Name"].ToString()  
  84.                 });  
  85.             }  
  86.             int skip = page.HasValue ? page.Value - 1 : 0;  
  87.             var data = lmd.OrderBy(o => o.SM_StudentID).Skip(skip * 5).Take(5).ToList();  
  88.             var grid = new WebGrid(data);  
  89.             var htmlString = grid.GetHtml(tableStyle: "webGrid",  
  90.                                           headerStyle: "header",  
  91.                                           alternatingRowStyle: "alt",  
  92.                                           htmlAttributes: new { id = "DataTable" });  
  93.             return Json(new  
  94.             {  
  95.                 Data = htmlString.ToHtmlString(),  
  96.                 Count = lmd.Count() / 5  
  97.             }, JsonRequestBehavior.AllowGet);  
  98.         }  
  99.     }  

Code description

The grid.Pager method sets the paging for the WebGrid. The problem is when you page through the data, all the data is returned. If you try to limit the data being returned, the problem you’ll encounter because you’re only returning a subset of the data is the WebGrid thinks there’s only that amount of data to display, so the paging links will disappear! Not good! So to show you what this looks like, I’m going to only return the first 5 records for the WebGrid, because I only want to display 5 records per page. Here’s my updated action method. 
  1. public ActionResult Index(int? page)  
  2.         {  
  3. return View(lmd.Take(5).ToList());  

Now because I’m returning only 5 instead of 10 records, the paging has disappeared from the WebGrid!

The WebGrid’s paging is it needs the total count of data that the grid is supposed to display. If you limit the WebGrid to only the records you want displayed, you limit the total count and the paging doesn’t work. To fix this problem you need to separate the two. One set of data for the grid and a separate piece of data that tells the WebGrid how many paging links to display. Unfortunately the paging object is locked, so I had to make my own. create an action method that returns the WebGrid as one object, and a total record count as another object and wrap both of them in a JSON object. Here’s the action method.

The JSON being returned stores two object
  • Data – this stores the data only needed for the grid. It utilizes the Skip and Take methods to limit the data being returned. It is returning the WebGrid as HTML. This ensures this code will replicate what the WebGrid would look like if we were declaring it in the Razor mark-up.
  • Count – this stores the total records. This will be used for creating the paging links.
iI you page through the data, the page you’re requesting will be sent as a parameter to the action method, and only that data will be fetched from the server.
  1. int skip = page.HasValue ? page.Value - 1 : 0;  
  2.             var data = lmd.OrderBy(o => o.SM_StudentID).Skip(skip * 5).Take(5).ToList();  
  3.             var grid = new WebGrid(data);  
  4.             var htmlString = grid.GetHtml(tableStyle: "webGrid",  
  5.                                           headerStyle: "header",  
  6.                                           alternatingRowStyle: "alt",  
  7.                                           htmlAttributes: new { id = "DataTable" });  
  8.             return Json(new  
  9.             {  
  10.                 Data = htmlString.ToHtmlString(),  
  11.                 Count = lmd.Count() / 5  
  12.             }, JsonRequestBehavior.AllowGet);  
  13.         } 
Code ref of Index.cshtml
  1. <body>  
  2.     @{  
  3.         var grid = new WebGrid(Model, canPage: true, rowsPerPage: 4);  
  4.         grid.Pager(WebGridPagerModes.NextPrevious);  
  5.         @grid.GetHtml(tableStyle: "table",  
  6.                 htmlAttributes: new { id = "DataTable" },  
  7.              headerStyle: "header"//applying style.    
  8.              footerStyle: "grid-footer"//applying style.    
  9.              alternatingRowStyle: "webgrid-alternating-row",  
  10.              rowStyle: "webgrid-row-style",  
  11.                 columns: grid.Columns(  
  12.                     grid.Column("SM_StudentID"),  
  13.                     grid.Column("SM_Name")  
  14.         ));  
  15.     }  
  16. </body> 
Code description

In this section the two columns are mentioned. 
  1. grid.Column("SM_StudentID"),  
  2. grid.Column("SM_Name"
Code ref of EfficientWay.cshtml
  1. <body>  
  2.     <script type="text/javascript" src="../../Scripts/jquery-1.10.2.js"></script>  
  3.     <script type="text/javascript" src="../../Scripts/Pager.js"></script>  
  4. </body> 
Code Description

Pager.js has the details about footer section that calls the EfficientPaging action and displays the returned WebGrid and creates the paging links.

OUTPUT

Custom Paging Link
 
 

Put Breakpoints and Debug To See the Page No. Using C#



Note


Creating your own paging links avoids repeated hits on the server which was creating a load on the server.

Summary
  • How to bind the WebGrid to the database and fetch the data.
  • Avoids hits on server by using Efficient Paging with WebGrid. 


Similar Articles