articles

Home / DeveloperSection / Articles / WebGrid in Asp.Net MVC 4

WebGrid in Asp.Net MVC 4

Sumit Kesarwani13060 04-Jun-2014

In this article, I’m explaining how to use webgrid in asp.net mvc.

WebGrid is use for displaying the data in tabular format 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 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 to set for the element.

 Example: 

First create a table in SQL Server database named “Student” like this:

WebGrid in Asp.Net MVC 4

And manually entered some data into table to show into the webgrid. 

Now create an asp.net mvc 4 web application:

WebGrid in Asp.Net MVC 4

WebGrid in Asp.Net MVC 4

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 { getset;}
        public string FirstName { getset; }
        public string LastName { getset; }
        public int Age { getset; }
        public string Gender { getset; }
        public string Batch { getset; }
        public string Address { getset; }
        public string Class { getset; }
        public string School { getset; }
        public string Domicile { getset; }
    }
}

Next add 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 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:

@model IEnumerable<WebGridinMVC.Models.StudentModel>
 
@{
    ViewBag.Title = "WebGridSample";
}
 
<h2>WebGridSample</h2>
<style type="text/css">
    .webGrid { margin4pxborder-collapsecollapsewidth500px;  background-color:#B4CFC3;}
    .header { background-color#C1D4E6font-weightboldcolor#FFF; }
    .webGrid th.webGrid td { border1px solid #C0C0C0padding5px; }
    .alt { background-color#E4E9F5color#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


Updated 07-Sep-2019

Leave Comment

Comments

Liked By