---
title: "WebGrid in Asp.Net MVC 4"  
description: "In this article, I’m explaining how to use webgrid in asp.net mvc."  
author: "Sumit Kesarwani"  
published: 2014-06-04  
updated: 2019-09-07  
canonical: https://www.mindstick.com/articles/1410/webgrid-in-asp-dot-net-mvc-4  
category: "asp.net"  
tags: ["asp.net"]  
reading_time: 4 minutes  

---

# WebGrid in Asp.Net MVC 4

In this article, I’m explaining how to use webgrid in asp.net mvc.

WebGrid is use for displaying the data in [tabular format](https://www.mindstick.com/forum/34668/how-to-embed-tabular-format-data-in-outlook-using-asp-dot-net-mvc) in asp.net mvc. WebGrid lets you render tabular data in a very simple manner with support for custom formatting of columns, paging, sorting and asynchronous updates via AJAX.

WebGrid Constructor Parameters

| ##### Name | ##### Type | ##### Notes |
| --- | --- | --- |
| source | IEnumerable<dynamic> | The data to render. |
| columnNames | IEnumerable<string> | Filters the columns that are rendered. |
| defaultSort | string | Specifies the default column to sort by. |
| rowsPerPage | int | Controls how many rows are rendered per page (default is 10). |
| canPage | bool | Enables or disables paging of data. |
| canSort | bool | Enables or disables sorting of data. |
| ajaxUpdateContainerId | string | The ID of the grid’s containing element, which enables AJAX support. |
| ajaxUpdateCallback | string | The client-side function to call when the AJAX update is complete. |
| fieldNamePrefix | string | Prefix for query string fields to [support multiple](https://www.mindstick.com/forum/159471/how-does-c-plus-plus-support-multiple-inheritance-and-what-are-potential-issues-associated-with-it) grids. |
| pageFieldName | string | Query string field name for page number. |
| selectionFieldName | string | Query string field name for selected row number. |
| sortFieldName | string | Query string field name for sort column. |
| sortDirectionFieldName | string | Query string field name for sort direction. |

WebGrid.GetHtml Parameters

| **Name** | **Type** | **Notes** |
| --- | --- | --- |
| tableStyle | string | Table class for styling. |
| headerStyle | string | Header row class for styling. |
| footerStyle | string | Footer row class for styling. |
| rowStyle | string | Row class for styling (odd rows only). |
| alternatingRowStyle | string | Row class for styling (even rows only). |
| selectedRowStyle | string | Selected row class for styling. |
| caption | string | The string displayed as the table caption. |
| displayHeader | bool | Indicates whether the header row should be displayed. |
| fillEmptyRows | bool | Indicates whether the table can add empty rows to ensure the rowsPerPage row count. |
| emptyRowCellValue | string | Value used to populate empty rows; only used when fillEmptyRows is set. |
| columns | IEnumerable<WebGridColumn> | Column model for customizing column rendering. |
| exclusions | IEnumerable<string> | Columns to exclude when auto-populating columns. |
| mode | WebGridPagerModes | Modes for pager rendering (default is NextPrevious and Numeric). |
| firstText | string | Text for a link to the first page. |
| previousText | string | Text for a link to the previous page. |
| nextText | string | Text for a link to the next page. |
| lastText | string | Text for a link to the last page. |
| numericLinksCount | int | Number of numeric links to display (default is 5). |
| htmlAttributes | object | Contains the [HTML attributes](https://www.mindstick.com/forum/160677/explain-about-html-attributes) to set for the element. |

##### Example:

First create a [table in SQL](https://www.mindstick.com/forum/205/find-the-all-column-with-schema-for-any-table-in-sql-server) [Server database](https://www.mindstick.com/forum/159667/how-to-migrate-the-sql-server-database-to-a-lower-version) named “Student” like this:

![WebGrid in Asp.Net MVC 4](http://www.mindstick.com/MindStickArticle/d7fbe906-ccb2-4f6e-8808-41931ed3b60a/Images/image001.png)

And manually entered some [data into table](https://www.mindstick.com/forum/172/how-v-insert-data-into-table-and-display-into-gridview-in-aspx-cs-file-with-out-using-wizard) to show into the webgrid.

Now create an asp.net mvc 4 [web application](https://www.mindstick.com/articles/13069/progressive-web-application-pwas-all-you-need-to-know-about):

![WebGrid in Asp.Net MVC 4](http://www.mindstick.com/MindStickArticle/d7fbe906-ccb2-4f6e-8808-41931ed3b60a/Images/image003.png)

![WebGrid in Asp.Net MVC 4](http://www.mindstick.com/MindStickArticle/d7fbe906-ccb2-4f6e-8808-41931ed3b60a/Images/image005.png)

Now create a model class named “StudentModel” like this:

```
using System;using System.Collections.Generic;using System.Linq;using System.Web; namespace WebGridinMVC.Models{    public class StudentModel    {        public string StudentId { get; set;}        public string FirstName { get; set; }        public string LastName { get; set; }        public int Age { get; set; }        public string Gender { get; set; }        public string Batch { get; set; }        public string Address { get; set; }        public string Class { get; set; }        public string School { get; set; }        public string Domicile { get; set; }    }}
```

Next add [connection string](https://www.mindstick.com/articles/17/connection-string) in the web.config file like this:

```
<connectionStrings>   <add name="ConnectionString" connectionString="Data Source=(local);Initial Catalog=SumitTesting;user id=USER ID;password=PASSWORD;"       providerName="System.Data.SqlClient"/> </connectionStrings>
```

After doing all these, next to create a controller and [action method](https://www.mindstick.com/forum/155751/define-action-method-in-mvc) to it:

```
using System;using System.Collections.Generic;using System.Configuration;using System.Data.SqlClient;using System.Linq;using System.Web;using System.Web.Mvc;using WebGridinMVC.Models; namespace WebGridinMVC.Controllers{    public class HomeController : Controller    {        //        // GET: /Home/         public ActionResult Index()        {            return View();        }         public ActionResult WebGridSample()        {            List<StudentModel> studentList = new List<StudentModel>();             try            {                string connString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;                using (SqlConnection conn = new SqlConnection(connString))                {                    conn.Open();                    SqlCommand cmd = new SqlCommand("Select * From Student", conn);                    SqlDataReader reader = cmd.ExecuteReader();                    while (reader.Read())                    {                        studentList.Add(new StudentModel                        {                            StudentId = reader["StudentId"].ToString(),                            FirstName = reader["FirstName"].ToString(),                            LastName = reader["LastName"].ToString(),                            Age = Convert.ToInt32(reader["Age"]),                            Gender = reader["Gender"].ToString(),                            Batch = reader["Batch"].ToString(),                            Address = reader["Address"].ToString(),                            Class = reader["Class"].ToString(),                            School = reader["School"].ToString(),                            Domicile = reader["Domicile"].ToString()                        });                    }                }                return View(studentList);            }            catch (Exception ex)            {                return View(studentList);            }        }     }}
```

After creating the controller, next is to create a view which will be [strongly typed](https://www.mindstick.com/forum/298/strongly-typed-view-in-mvc):

```
@model IEnumerable<WebGridinMVC.Models.StudentModel> @{    ViewBag.Title = "WebGridSample";} <h2>WebGridSample</h2><style type="text/css">    .webGrid { margin: 4px; border-collapse: collapse; width: 500px;  background-color:#B4CFC3;}    .header { background-color: #C1D4E6; font-weight: bold; color: #FFF; }    .webGrid th, .webGrid td { border: 1px solid #C0C0C0; padding: 5px; }    .alt { background-color: #E4E9F5; color: #000; }    .gridHead a:hover {text-decoration:underline;}    .description { width:auto}    .select{background-color: #71857C}</style>  @{    WebGridinMVC.Models.StudentModel student = new WebGridinMVC.Models.StudentModel();} @{    var grid = new WebGrid(Model, canPage: true, rowsPerPage: 10,    selectionFieldName: "selectedRow", ajaxUpdateContainerId: "gridContent");    grid.Pager(WebGridPagerModes.NextPrevious);} <div id="gridContent">    @grid.GetHtml(tableStyle: "webGrid",            headerStyle: "header",            alternatingRowStyle: "alt",            selectedRowStyle: "select",            columns: grid.Columns(            grid.Column("FirstName", "FirstName"),            grid.Column("LastName", "LastName"),            grid.Column("Age", "Age"),            grid.Column("Gender", "Gender"),            grid.Column("Batch", "Batch"),            grid.Column("Address", "Address"),            grid.Column("Class", "Class"),            grid.Column("School", "School"),            grid.Column("Domicile", "Domicile")     ))</div>
```

Now open “RouteConfig.cs” file and change the action name from “Index” to

“WebGridSample” like this:

```
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using System.Web.Routing; namespace WebGridinMVC{    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 = "WebGridSample", id = UrlParameter.Optional }            );        }    }}
```

##### Output

Now run the application:

![WebGrid in Asp.Net MVC 4](http://www.mindstick.com/MindStickArticle/d7fbe906-ccb2-4f6e-8808-41931ed3b60a/Images/image007.png)

---

Original Source: https://www.mindstick.com/articles/1410/webgrid-in-asp-dot-net-mvc-4

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
