DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Optimizing Data Loader Jobs in SQL Server: Production Implementation Strategies
  • Beyond Partitioning and Z-Order: A Deep Dive into Liquid Clustering for Unity Catalog Managed Tables
  • One Query, Four GPUs: Tracing a Distributed Training Stall Across Nodes
  • Why We Chose Iceberg Over Delta After Evaluating Both at Scale

Trending

  • Smart Deployment Strategies for Modern Applications
  • Key Takeaways From Integrating a RAG Application With LangSmith
  • Introduction to Tactical DDD With Java: Steps to Build Semantic Code
  • OpenAPI From Code With Spring and Java: A Recipe for Your CI
  1. DZone
  2. Data Engineering
  3. Databases
  4. Basic Implementation of WebGrid Control in MVC 5

Basic Implementation of WebGrid Control in MVC 5

In this post, we will take a look at how we can write code in ASP.NET MVC that will implement WebGrid Control using Static Data.

By 
Satyaprakash Samantaray user avatar
Satyaprakash Samantaray
·
Jun. 06, 18 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
42.4K Views

Join the DZone community and get the full member experience.

Join For Free

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

In this post, I will show you how to write code in ASP.NET MVC that will implement 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 the Models folder, Employee.cs.
    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Web;  
    namespace WebgridOrGridview.Models {  
        public class Employee {  
            public string FirstName {  
                get;  
                set;  
            }  
            public string LastName {  
                get;  
                set;  
            }  
            public double Salary {  
                get;  
                set;  
            }  
            public static List < Employee > GetList() {  
                List < Employee > Employees = new List < Employee > {  
                    new Employee {  
                        FirstName = "Satyaprakash1", LastName = "Samantaray1", Salary = 45000  
                    },  
                    new Employee {  
                        FirstName = "Satyaprakash2", LastName = "Samantaray2", Salary = 25000  
                    },  
                    new Employee {  
                        FirstName = "Satyaprakash3", LastName = "Samantaray3", Salary = 25000  
                    },  
                    new Employee {  
                        FirstName = "Satyaprakash4", LastName = "Samantaray4", Salary = 35000  
                    },  
                    new Employee {  
                        FirstName = "Satyaprakash5", LastName = "Samantaray5", Salary = 65000  
                    },  
                    new Employee {  
                        FirstName = "Satyaprakash6", LastName = "Samantaray6", Salary = 75000  
                    },  
                    new Employee {  
                        FirstName = "Satyaprakash7", LastName = "Samantaray7", Salary = 85000  
                    },  
                    new Employee {  
                        FirstName = "Satyaprakash8", LastName = "Samantaray8", Salary = 95000  
                    },  
                };  
                return Employees;  
            }  
        }  
    }  

Here, I have added some static data which can be shown in rows of WebGrid.

3. Create a Controller named HomeController.cs.

    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Web;  
    using System.Web.Mvc;  
    using WebgridOrGridview.Models;  
    namespace WebgridOrGridview.Controllers {  
        public class HomeController: Controller {  
            public ActionResult show() {  
                var empoyees = Employee.GetList(); //Reference of Model Class File.  
                return View(empoyees);  
            }  
        }  
    }  

4. Add a View in the Views folder named show.cshtml.

    @ * @model IEnumerable < WebgridOrGridview.Models.Employee > * @  
    @ {  
        Layout = null;  
    }  
    @ {  
        var grid = new WebGrid(source: Model, defaultSort: "FirstName", rowsPerPage: 3);  
    } < h2 style = "color:blue" > Web Grid In MVC4 < /h2> < style type = "text/css" >  
        /*Here we will add css for style webgrid*/  
        .webgrid - table {  
            font - family: "Trebuchet MS", Arial, Helvetica, sans - serif;  
            font - size: 1.2e m;  
            width: 100 % ;  
            display: table;  
            border - collapse: separate;  
            border: solid 1 px blue;  
            background - color: white;  
        }.webgrid - table td, th {  
            border: 1 px solid blue;  
            padding: 3 px 7 px 2 px;  
        }.webgrid - header {  
            background - color: yellow;  
            color: red;  
            padding - bottom: 4 px;  
            padding - top: 5 px;  
            text - align: left;  
        }  
        /*.webgrid-footer { 

        }*/  
        .webgrid - row - style {  
            padding: 3 px 7 px 2 px;  
        }.webgrid - alternating - row {  
            background - color: pink;  
            padding: 3 px 7 px 2 px;  
        } /*for alteranating row style*/ < /style> < div id = "grid" > @grid.GetHtml(tableStyle: "webgrid-table", headerStyle: "webgrid-header",  
            //footerStyle: "webgrid-footer",  
            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  
            columns: grid.Columns(grid.Column("FirstName"), grid.Column("LastName"), grid.Column("Salary")  
                //grid.Column(header: "Action",format:@<text>@Html.ActionLink("Modify","") | @Html.ActionLink("Detail", "")| @Html.ActionLink("Remove", "")</text>) @*format: @<text>[email protected]</text>*@ @*Format of currency*@  
            )) < /div>  

5. In show.chtml, add one Class that references WebGrid.

    @ {  
        var grid = new WebGrid(source: Model, defaultSort: "FirstName", rowsPerPage: 3);  
    }  
    //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 another way. Right click on WebGrid in show.cshtml and "Go To Definition."

8. Then, the Metadata definition file for this WebGrid will be shown.

    #region Assembly System.Web.Helpers.dll, v2 .0 .0 .0  
    // C:\Users\Satya\Desktop\Satyaa\Training Task\Mvc Apps\WebgridOrGridview\packages\Microsoft.AspNet.WebPages.2.0.30506.0\lib\net40\  
    System.Web.Helpers.dll  
    # endregion  

i.e. WebGrid[from metadata]

9. Then, add some code to the RouteConfig.cs file for the Action Method name, as we mentioned in Controller section.

    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Web;  
    using System.Web.Mvc;  
    using System.Web.Routing;  
    namespace WebgridOrGridview {  
        public class RouteConfig {  
            public static void RegisterRoutes(RouteCollection routes) {  
                routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
                routes.MapRoute(name: "Default", url: "{controller}/{action}/{id}", defaults: new {  
                    controller = "Home", action = "show", id = UrlParameter.Optional  
                });  
            }  
        }  
    }  


  1. The URL can found when we run this MVC application.

http://localhost:53848/Home/show

Controller Name: Home

Controller Action Method Name: show

Output:

Image title

Add pagination in WebGrid in show.cshtml.

    <div id="grid">  
        @grid.GetHtml(  
            tableStyle: "webgrid-table",  
            headerStyle: "webgrid-header",  
            //footerStyle: "webgrid-footer",  
            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  
            columns: grid.Columns(  
                grid.Column("FirstName"),  
                grid.Column("LastName"),  
                grid.Column("Salary")  
                //grid.Column(header: "Action",format:@<text>@Html.ActionLink("Modify","") | @Html.ActionLink("Detail", "")| @Html.ActionLink("Remove", "")</text>)    @*format: @<text>[email protected]</text>*@ @*Format of currency*@  
                            )  
                        )  
    </div>   

When we go to the next page by Page Check, the URL is changed based on the 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

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

These are all available as link formats in WebGrid. 

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 the FirstName link again in WebGrid, the URL is changed to show the records under this column in descending order.

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

Like this, in LastName., the 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 the sorting order of Values in one column, the other column values will also be sorted accordingly and automatically.

Image title

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

Happy coding and best of luck!

sql Implementation ASP.NET MVC

Opinions expressed by DZone contributors are their own.

Related

  • Optimizing Data Loader Jobs in SQL Server: Production Implementation Strategies
  • Beyond Partitioning and Z-Order: A Deep Dive into Liquid Clustering for Unity Catalog Managed Tables
  • One Query, Four GPUs: Tracing a Distributed Training Stall Across Nodes
  • Why We Chose Iceberg Over Delta After Evaluating Both at Scale

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook