In this article I will explain with a step by step tutorial with an example, how to use
WebGrid in ASP.Net MVC.
1. Display specific columns in
WebGrid.
Database
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
Creating an Entity Data Model
The very first step is to create an ASP.Net MVC Application and connect it to the Database using
Entity Framework.
Note: For beginners in ASP.Net MVC and
Entity Framework, please refer my article ASP.Net MVC: Simple Entity Framework Tutorial with example. It covers all the information needed for connecting and configuring
Entity Framework.
Following is the Entity Data Model of the Customers table which will be used later in this project.
Namespace
You will need to import the following namespace.
Controller
The Controller consists of following Action method.
Action method for handling GET operation
Inside the Index Action method, the records are fetched from the
Customers table of the
Northwind database using
Entity Framework and returned to the View.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
NorthwindEntities entities = new NorthwindEntities();
return View(entities.Customers.ToList());
}
}
View
HTML Markup
Inside the View, in the very first line the Customer Entity is declared as IEnumerable which specifies that the Model will be available as a Collection.
The
WebGrid is initialized with the Model i.e.
IEnumerable collection of
Customer Entity class objects as source.
The
WebGrid is created using the
GetHtml method with the following parameters.
htmlAttributes – It is used to set the HTML attributes to the HTML Table generated by
WebGrid such as id, name, class, etc.
columns – It is used to specify the columns to be displayed in
WebGrid and it also used to set specific Header Text for the columns.
Note: If the columns are not specified then
WebGrid will display all columns supplied by its source. It is very similar to the
AutoGenerateColumns feature of the ASP.Net GridView.
@model IEnumerable<WebGrid_EF_MVC.Customer>
@{
Layout = null;
WebGrid webGrid = new WebGrid(source: Model);
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
@webGrid.GetHtml(
htmlAttributes:new { @id = "WebGrid", @class = "Grid" },
columns:webGrid.Columns(
webGrid.Column("CustomerID", "Customer Id"),
webGrid.Column("ContactName", "Customer Name"),
webGrid.Column("City", "City"),
webGrid.Column("Country", "Country")))
</body>
</html>
Screenshot
Downloads