Web Tutorials

HTML Tutorial
HTML5 Tutorial
Bootstrap3 Tutorial
Javascript Tutorial
TypeScript Tutorial
AngularJS Tutorial
CSharp Tutorial
.NET Tutorial
PHP Tutorial

Interview Q & A

ASP.NET Q & A
WEB API Q & A
WCF Q & A
JQuery Q & A
MVC Q & A
Bootstrap Q & A
LINQ Q & A
AJAX Q & A
SQL Server Q & A
C# Q & A
OOPS Q & A

Code Examples

AngularJS
Google MAP API V3
ASP.NET

Utility Tools

Html Encode
Html Decode
URL Decode
URL Encode
Base64 Encode
Base64 Decode
JSON Beautifier

WebGrid in MVC 5 with Razor view and Entity Framework 6

Posted By: Ajay Saptaputre, 11 Oct,2015  |  Total View : 54144

In my previous article I discussed about create CRUD operation using Scaffolding with ASP.NET MVC 5 and database first approach using ASP.NET MVC 5 and Entity Framework 6 and model first approach using ASP.NET MVC 5 and Entity Framework 6

In this article I am going to discuss how to bind data from database to WebGrid. Basically WebGrid is used to display data on a web page using HTML table elements. It renders data in tabular format and also supports custom formatting of columns, paging, sorting, and asynchronous updates via AJAX. Grid is very useful and powerful tool to present data in tabular manner with look and feel.

ASP.NET MVC does not have any built in data binding controls like GridView, DetailsView etc. WebGrid provides similar functionality like other data binding controls provides like sorting, paging, ordering, column formatting etc. WebGrid makes developers life easy and saves there time rather he has to write code to display data in tabular manner.

In order to start our sample application we will need database table, entity and DBContect classes to fetch the data from database. In this article I am not covering steps those are already covered in my previous article. If you did not read, please refer database first approach using ASP.NET MVC 5 and Entity Framework 6 and follow Step 1 to Step 16 it will help you to understand this article.

Step 1: I hope you already red my previous article. Now, right click on Controller folder and select Controller from menu as below screen shot.


Step 2: Select MVC 5 empty controller, rename controller name as "EmployeeController". Click on "Add" button.


Step 3: Now add below code to controller class. The below code will send list of "Employee" object to view.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCDisplayWebGrid.Models;

namespace MVCDisplayWebGrid.Controllers
{
    public class EmployeeController : Controller
    {
        public ActionResult Index()
        {
            EmployeeDBContext db = new EmployeeDBContext();
            return View(db.Employees.ToList());
        }
	}
}

Step 4: Now right click on "Index" action method, select "Add View" and select "Empty" template from dropdown. To build view we will need to specify model class as "Employee" and data context class as "EmployeeDBContext" as below screen shot illustrate. Click "Add" button. This will add IEnumerable Employee object in view page as below.


@model IEnumerable<MVCDisplayWebGrid.Models.Employee>

Step 5: WebGrid Auto Sorting and Paging
Now instantiate WebGrid control and hands over Model to it. Now call GetHtml() method of WebGrid to display simple data list with all the columns that includes default sorting and paging functionality. See below code snippet screen shot:

@{
    ViewBag.Title = "WebGrid Example";
    var grid = new WebGrid(source: Model);
}
@grid.GetHtml();

Step 6: WebGrid Without Sorting
If suppose you don't want sorting in WebGrid, simply set canSort property to false. See below code snippet screen shot:

@{
    ViewBag.Title = "WebGrid Example";
    var grid = new WebGrid(source: Model,canSort:false);
}
@grid.GetHtml();

Step 7: WebGrid Display Only Specific Columns
In case you want to display only certain columns in WebGrid list, you can do it by simply setting columnNames property to <string array>. See below code snippet screen shot:

@{
    ViewBag.Title = "WebGrid Example";
    var grid = new WebGrid(source: Model, columnNames: new[] 
	{ "Name", "Designation", "Gender", "Salary" });
}
@grid.GetHtml();

Step 8: WebGrid Rows per Page
In case you want increase or decrease rows per page you can do it by simply setting rowsPerPage property to <number>. See below code snippet:

@{
    ViewBag.Title = "WebGrid Example";
    var grid = new WebGrid(source: Model, rowsPerPage: 3);
}
@grid.GetHtml();

Step 9: WebGrid Specify Default Sorting Field
In case you want to add sorting on specific field in WebGrid, simply set defaultSort property to <yourfield>. See below code snippet:

@{
    ViewBag.Title = "WebGrid Example";
    var grid = new WebGrid(source: Model, defaultSort: "Name");
}
@grid.GetHtml();

Step 10: WebGrid Specify Custom Header
There are situations where you may asked to change the actual column name before display to the user. In order to do that we need to specify property called columns , which accept collection of grid.Column with <actualFieldName> and changed header name <changedHeaderName>. See below code snippet and screen shot:

@{
    ViewBag.Title = "WebGrid Example";
    var grid = new WebGrid(source: Model, columnNames: new[] 
	{ "Name", "Designation", "Gender", "Salary" });
}
@grid.GetHtml(columns: grid.Columns(
grid.Column(columnName: "Name", header: "Employee Name"),
grid.Column(columnName: "Designation", header: "Employee Designation"),
grid.Column(columnName: "Gender", header: "Employee Gender"),
grid.Column(columnName: "Salary", header: "Salary"),
grid.Column(columnName: "City", header: "City"),
grid.Column(columnName: "State", header: "State"),
grid.Column(columnName: "Zip", header: "Zip")
    ))

Step 11: WebGrid Add Custom Column
WebGrid allows us to add custom column as well. To add a custom column to the WebGrid, we need to use grid.Column method by specifying format attribute to the template that we want to use. In the below code snippet when user clicks on "Edit" link for specific "Employee", it will send the selected "Id" to edit the employee. All right, so let's quickly add custom column in WebGrid. See below code snippet and screen shot:

@{
    ViewBag.Title = "WebGrid Example";
    var grid = new WebGrid(source: Model, columnNames: new[] 
	{ "Name", "Designation", "Gender", "Salary" });
}
@grid.GetHtml(columns: grid.Columns(
grid.Column(columnName: "Name", header: "Employee Name"),
grid.Column(columnName: "Designation", header: "Employee Designation"),
grid.Column(columnName: "Gender", header: "Employee Gender"),
grid.Column(columnName: "Salary", header: "Salary"),
grid.Column(columnName: "City", header: "City"),
grid.Column(columnName: "State", header: "State"),
grid.Column(columnName: "Zip", header: "Zip"),
grid.Column(header: "Edit", format: (item) =>
{
	var link = Html.ActionLink("Edit", "Edit", new { id = item.Id });
	return link;
})
    ))

Step 12: WebGrid Applying Style to Rows and Columns
In order to apply custom theme or CSS style to WebGrid you need to create css classes first and set respective properties of the WebGrid. See below code snippet and screen shot:

<style type="text/css">
    .webgrid-table {
        font-family: Arial,Helvetica,sans-serif;
        font-size: 14px;
        font-weight: normal;
        width: 650px;
        display: table;
        border-collapse: collapse;
        border: solid px #C5C5C5;
        background-color: white;
    }
	.webgrid-table td, th {
		border: 1px solid #C5C5C5;
		padding: 3px 7px 2px;
	}
    .webgrid-header, .webgrid-header a {
        background-color: #0094ff;
        color:#ffffff;
        text-align: left;
        text-decoration: none;
    }
    .webgrid-footer {
    }
    .webgrid-row-style {
        padding: 3px 7px 2px;
    }
    .webgrid-alternating-row {
        background-color:azure;
        padding: 3px 7px 2px;
    }
    .col1Width {
        width: 55px;
    }
    .col2Width {
        width: 220px;
    }
</style>

@{
    ViewBag.Title = "WebGrid Example";
    var grid = new WebGrid(source: Model, canPage: true, rowsPerPage: 3);
    grid.Pager(WebGridPagerModes.All);
}
<div id="gridContent" style="font-family: Arial; padding: 20px;">
    @grid.GetHtml(tableStyle: "webgrid-table",
    headerStyle: "webgrid-header",
    footerStyle: "webgrid-footer",
    alternatingRowStyle: "webgrid-alternating-row",
    selectedRowStyle: "webgrid-selected-row",
    rowStyle: "webgrid-row-style",
    columns: grid.Columns(
                grid.Column(columnName: "Name", header: "Name"),
                grid.Column(columnName: "Designation", header: "Designation"),
                grid.Column(columnName: "Gender", header: "Gender"),
                grid.Column(columnName: "Salary", header: "Salary"),
                grid.Column(columnName: "City", header: "City"),
                grid.Column(columnName: "State", header: "State"),
                grid.Column(columnName: "Zip", header: "Zip")

    ))
</div>

Step 13: WebGrid Row Selection
In order to provide row selection in WebGrid, set formatting by calling GetSelectLink method to a specific column. You may notice that first Column (Id) specified as link to selected WebGrid row. To display selected row data, I am checking selected row using grid.HasSelection property. If yes, I am casting grid row back to our "Employee" object and displaying object properties. See below code snippet and screen shot:

@{
    ViewBag.Title = "WebGrid Example";
    var grid = new WebGrid(source: Model, canPage: true, rowsPerPage: 3);
    grid.Pager(WebGridPagerModes.All);
}

<div id="gridContent" style="font-family: Arial; padding: 20px;">
    @grid.GetHtml(tableStyle: "webgrid-table",
    headerStyle: "webgrid-header",
    footerStyle: "webgrid-footer",
    alternatingRowStyle: "webgrid-alternating-row",
    selectedRowStyle: "webgrid-selected-row",
    rowStyle: "webgrid-row-style",
    columns: grid.Columns(
                grid.Column("Id", format :(item) => item.GetSelectLink(item.Id.ToString())),
                grid.Column(columnName: "Designation", header: "Designation"),
                grid.Column(columnName: "Gender", header: "Gender"),
                grid.Column(columnName: "Salary", header: "Salary"),
                grid.Column(columnName: "City", header: "City"),
                grid.Column(columnName: "State", header: "State"),
                grid.Column(columnName: "Zip", header: "Zip")

    ))
    <h2>Your Selected Row</h2>
    @if (grid.HasSelection)
    {
        var emp = (MVCDisplayWebGrid.Models.Employee)grid.Rows[grid.SelectedIndex].Value;
        <p><b>Employee Name:</b> @emp.Name</p>
        <p><b>Employee Designation:</b> @emp.Designation</p>
        <p><b>Employee Gender:</b> @emp.Gender</p>
        <p><b>Employee Salary:</b> @emp.Salary</p>
        <p><b>City:</b> @emp.City</p>
        <p><b>State:</b> @emp.State</p>
        <p><b>Zip:</b> @emp.Zip</p>
    }
</div>

Appreciate your valuable feedback:

I hope this article is useful for you. I look forward for your comments and feedback. So please provide your valuable feedback so that I can make this blog better. You can also share this article by hitting below button.
Happy learning...

Download Code ⇩