Basic Implementation Of WebGrid Control In ASP.NET MVC 4.0

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.

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 SQL Server data source.

Steps for creating WebGrid

  1. First, create an application named WebgridOrGridview.



  2. Create a Class file in Models folder Employee.cs.
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Web;  
    5. namespace WebgridOrGridview.Models {  
    6.     public class Employee {  
    7.         public string FirstName {  
    8.             get;  
    9.             set;  
    10.         }  
    11.         public string LastName {  
    12.             get;  
    13.             set;  
    14.         }  
    15.         public double Salary {  
    16.             get;  
    17.             set;  
    18.         }  
    19.         public static List < Employee > GetList() {  
    20.             List < Employee > Employees = new List < Employee > {  
    21.                 new Employee {  
    22.                     FirstName = "Satyaprakash1", LastName = "Samantaray1", Salary = 45000  
    23.                 },  
    24.                 new Employee {  
    25.                     FirstName = "Satyaprakash2", LastName = "Samantaray2", Salary = 25000  
    26.                 },  
    27.                 new Employee {  
    28.                     FirstName = "Satyaprakash3", LastName = "Samantaray3", Salary = 25000  
    29.                 },  
    30.                 new Employee {  
    31.                     FirstName = "Satyaprakash4", LastName = "Samantaray4", Salary = 35000  
    32.                 },  
    33.                 new Employee {  
    34.                     FirstName = "Satyaprakash5", LastName = "Samantaray5", Salary = 65000  
    35.                 },  
    36.                 new Employee {  
    37.                     FirstName = "Satyaprakash6", LastName = "Samantaray6", Salary = 75000  
    38.                 },  
    39.                 new Employee {  
    40.                     FirstName = "Satyaprakash7", LastName = "Samantaray7", Salary = 85000  
    41.                 },  
    42.                 new Employee {  
    43.                     FirstName = "Satyaprakash8", LastName = "Samantaray8", Salary = 95000  
    44.                 },  
    45.             };  
    46.             return Employees;  
    47.         }  
    48.     }  
    49. }  
    Here, I have added some static data which can be shown in rows of WebGrid.



  3. Create a Controller named HomeController.cs.
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Web;  
    5. using System.Web.Mvc;  
    6. using WebgridOrGridview.Models;  
    7. namespace WebgridOrGridview.Controllers {  
    8.     public class HomeController: Controller {  
    9.         public ActionResult show() {  
    10.             var empoyees = Employee.GetList(); //Reference of Model Class File.  
    11.             return View(empoyees);  
    12.         }  
    13.     }  
    14. }  

  4. Add a View in Views folder named show.cshtml.
    1. @ * @model IEnumerable < WebgridOrGridview.Models.Employee > * @  
    2. @ {  
    3.     Layout = null;  
    4. }  
    5. @ {  
    6.     var grid = new WebGrid(source: Model, defaultSort: "FirstName", rowsPerPage: 3);  
    7. } < h2 style = "color:blue" > Web Grid In MVC4 < /h2> < style type = "text/css" >  
    8.     /*Here we will add css for style webgrid*/  
    9.     .webgrid - table {  
    10.         font - family: "Trebuchet MS", Arial, Helvetica, sans - serif;  
    11.         font - size: 1.2e m;  
    12.         width: 100 % ;  
    13.         display: table;  
    14.         border - collapse: separate;  
    15.         border: solid 1 px blue;  
    16.         background - color: white;  
    17.     }.webgrid - table td, th {  
    18.         border: 1 px solid blue;  
    19.         padding: 3 px 7 px 2 px;  
    20.     }.webgrid - header {  
    21.         background - color: yellow;  
    22.         color: red;  
    23.         padding - bottom: 4 px;  
    24.         padding - top: 5 px;  
    25.         text - align: left;  
    26.     }  
    27.     /*.webgrid-footer { 
    28.  
    29.     }*/  
    30.     .webgrid - row - style {  
    31.         padding: 3 px 7 px 2 px;  
    32.     }.webgrid - alternating - row {  
    33.         background - color: pink;  
    34.         padding: 3 px 7 px 2 px;  
    35.     } /*for alteranating row style*/ < /style> < div id = "grid" > @grid.GetHtml(tableStyle: "webgrid-table", headerStyle: "webgrid-header",  
    36.         //footerStyle: "webgrid-footer",  
    37.         alternatingRowStyle: "webgrid-alternating-row", rowStyle: "webgrid-row-style", mode: WebGridPagerModes.All, firstText: "<< First", previousText: "< Prev", nextText: "Next >", lastText: "Last >>"//add next or prev link in webgrid  
    38.         columns: grid.Columns(grid.Column("FirstName"), grid.Column("LastName"), grid.Column("Salary")  
    39.             //grid.Column(header: "Action",format:@<text>@Html.ActionLink("Modify","") | @Html.ActionLink("Detail", "")| @Html.ActionLink("Remove", "")</text>) @*format: @<text>$@item.Salary</text>*@ @*Format of currency*@  
    40.         )) < /div>  


  5. In show.chtml, add one Class that references WebGrid.
    1. @ {  
    2.     var grid = new WebGrid(source: Model, defaultSort: "FirstName", rowsPerPage: 3);  
    3. }  
    4. //We can add Max No. of pages in webgrid when the page loads  
  6. To get this WebGrid reference, we have to add some assembly / DLL reference in "References" folder i.e. System.Web.Helpers.dll.



  7. Also, we can check this WebGrid Reference mentioned in Show.Cshtml in other way. Right click on WebGrid in show.cshtml and "Go To Definition".



  8. Then, the Metadata definition file for this WebGrid will be shown.
    1. #region Assembly System.Web.Helpers.dll, v2 .0 .0 .0  
    2. // C:\Users\Satya\Desktop\Satyaa\Training Task\Mvc Apps\WebgridOrGridview\packages\Microsoft.AspNet.WebPages.2.0.30506.0\lib\net40\  
    3. System.Web.Helpers.dll  
    4. # endregion  
    i.e. WebGrid[from metadata]

  1. Then, add some code RouteConfig.cs file for Action Method name, as we mentioned in Controller section.
    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. namespace WebgridOrGridview {  
    8.     public class RouteConfig {  
    9.         public static void RegisterRoutes(RouteCollection routes) {  
    10.             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
    11.             routes.MapRoute(name: "Default", url: "{controller}/{action}/{id}", defaults: new {  
    12.                 controller = "Home", action = "show", id = UrlParameter.Optional  
    13.             });  
    14.         }  
    15.     }  
    16. }  

  1. The URL will be found when we run this MVC application.

http://localhost:53848/Home/show

Controller Name : Home

Controller Action Method Name : show

Output 1


Output 2

Add pagination in WebGrid in Show.Cshtml.

  1. <div id="grid">  
  2.     @grid.GetHtml(  
  3.         tableStyle: "webgrid-table",  
  4.         headerStyle: "webgrid-header",  
  5.         //footerStyle: "webgrid-footer",  
  6.         alternatingRowStyle: "webgrid-alternating-row",  
  7.         rowStyle: "webgrid-row-style",  
  8.         mode: WebGridPagerModes.All,  
  9.         firstText: "<< First",  
  10.         previousText: "< Prev",  
  11.         nextText: "Next >",  
  12.         lastText: "Last >>"//add next or prev link in webgrid  
  13.         columns: grid.Columns(  
  14.             grid.Column("FirstName"),  
  15.             grid.Column("LastName"),  
  16.             grid.Column("Salary")  
  17.             //grid.Column(header: "Action",format:@<text>@Html.ActionLink("Modify","") | @Html.ActionLink("Detail", "")| @Html.ActionLink("Remove", "")</text>)    @*format: @<text>$@item.Salary</text>*@ @*Format of currency*@  
  18.                         )  
  19.                     )  
  20. </div>   

When we go to the next page by Page Check, the URL is changed based on Page No. Index in WebGrid.

When we go to page 1, the URL is changed to >>  http://localhost:53848/Home/show?page=1


When we go to page 2, the URL is changed to >> http://localhost:53848/Home/show?page=2


When we go to page 3, the URL is changed to >> http://localhost:53848/Home/show?page=3


Output

There are 3 columns in WebGrid i.e. FirstName, LastName, and Salary. 

These are all available as link formats in WebGrid. 

  1. columns: grid.Columns(grid.Column("FirstName"), grid.Column("LastName"), grid.Column("Salary")   

When we click FirstName link in WebGrid, the URL is changed as Records under this column name, in ascending order.

  • http://localhost:53848/Home/show?sort=FirstName&sortdir=ASC

When we click FirstName link again in WebGrid, the URL is changed as Records under this column name, in descending order.

  • http://localhost:53848/Home/show?sort=FirstName&sortdir=DESC

Like this, in LastName and Salary Column Values are sorted in ascending and descending order.

  • http://localhost:53848/Home/show?sort=LastName&sortdir=ASC



  • http://localhost:53848/Home/show?sort=LastName&sortdir=DESC



  • http://localhost:53848/Home/show?sort=Salary&sortdir=ASC



  • http://localhost:53848/Home/show?sort=Salary&sortdir=DESC


Based on sorting order of Values in one column, the other column values will also be sorted accordingly and automatically.


Like this, we can add WebGrid in ASP.NET MVC and related properties for WebGrid in show.cshtml file.

Happy Coding….

Best Of luck.