This is a continuation of Part 5. If you are new to MVC then I strongly recommend you go through Part Four before proceeding with this article. Click the following links for the previous parts of this tutorial.
In the last tutorial we see how to customize the Index view and create search paging and sorting functionality for the view. Note that from that tutorial you have absorbed how to implement all of that functionality in a HTML table manually with a lot of code and logic. We can easily do all that functionality in ASP.NET easily using a GridView control. In MVC we are missing @Html.Grid() kind of things right now.
In this tutorial we will create a grid and implement all the functionality using that grid. For creating and using a Grid in ASP.Net MVC we need to use the following procedure. We will continue with the example we were using in the last article. In MVC a grid is known as a Webgrid.
A Webgrid is used to display data on a web page using an HTML table element. It has built-in support for paging and sorting. You can style a webgrid easily using the alternatingRowStyle, headerStyle or tableStyle attributes.
Here is a link to the MSDN for the WebGrid Class.
Step 1
Open the last project that we were working on and go to EmployeeContoller and create an action method that will return the simple list of employees like:
- public ActionResult EmpListUsingGrid()
- {
- return View(db.Employees.ToList());
- }
Step 2
Now right-click anywhere on this action method and click on Add view and select List from the template dropdown and also select Employee as the Model class and add the view.
Step 3
Delete all the default code except following in that view.
- @model IEnumerable<CodeFirstApproachWithEmployeesInfo.Models.Employee>
Note: If you select Empty as the template then we need to add the preceding code to that view.
Step 4
Now our first task is to display the employees list in the web grid. For doing that we need to write the following code.
- <h2>List of Employees in Web Grid</h2>
-
- @{
- var grid = new WebGrid(source: Model);
- @grid.GetHtml(tableStyle: "table",columns: grid.Columns(
- grid.Column("EmpName"),
- grid.Column("Gender"),
- grid.Column("EmailId"),
- grid.Column("Salary"),
- grid.Column("MobileNo", header: "Mobile"),
- grid.Column("Department", format: @<text>@item.Department.DeptName</text>),
- grid.Column("EmpDOB")));
- }
grid.Column("EmpName") has several overloaded constructors. In the preceding case the name of the field must match the name of the field in the Employee class.
![Employee class]()
The following line of code will display the name of the department by using the Department navigation property of the employee class.
grid.Column("Department", format: @<text>@item.Department.DeptName</text>)
That's it. Run the project and you will get the following output:
![table]()
Note: In the preceding image header the field is by default highlighted and when you click on the header the sorting is happening by default. If you turn off sorting for any field then just add the following code for that field:
grid.Column("Salary", canSort: false)
If you want to disable the sorting for the entire grid then use:
var grid = new WebGrid(source: Model, canSort: false);
That line of code disables sorting for a webgrid.
Paging in WebGrid
For enabling paging in a grid we need to modify the preceding grid code as:
- var grid = new WebGrid(source: Model,canPage :true,rowsPerPage:3);
or alternatively:
- var grid = new WebGrid(source: Model,rowsPerPage:3);
-
- If you use var grid = new WebGrid(source: Model,canPage: true);
The default page side will take 10 I think.
Note: when we perform sorting and paging look at the change in URL. The entire task that we implement in previous session is doing by webgrid automatically.
The View code will look like:
- @model IEnumerable<CodeFirstApproachWithEmployeesInfo.Models.Employee>
-
- @{
- ViewBag.Title = "EmpListUsingGrid";
- }
-
- <h2>List Of Employees In Web Grid</h2>
-
- @{
- var grid = new WebGrid(source: Model, canPage: true);
- @grid.GetHtml(tableStyle: "table", htmlAttributes: new { id = "DataTable" }, columns: grid.Columns(
- grid.Column("EmpName"),
- grid.Column("Gender"),
- grid.Column("EmailId"),
- grid.Column("Salary"),
- grid.Column("MobileNo", header: "Mobile"),
- grid.Column("Department", format: @<text>@item.Department.DeptName</text>),
- grid.Column("EmpDOB")));
- }
Run the view and see the output like:
If we want to modify the page number style by adding a next and previous then we need to make a small modification in our code like:
- @model IEnumerable<CodeFirstApproachWithEmployeesInfo.Models.Employee>
- <h2>List Of Employees In Web Grid</h2>
- @{
- var grid = new WebGrid(source: Model, canPage: true, rowsPerPage: 2);
- @grid.GetHtml(tableStyle: "table",
- mode: WebGridPagerModes.All,
-
- firstText: "<< First",
- previousText: "< Previous ",
- nextText: "Next >",
- lastText: "Last >>",
- htmlAttributes: new { id = "DataTable" }, columns: grid.Columns(
- grid.Column("EmpName"),
- grid.Column("Gender"),
- grid.Column("EmailId"),
- grid.Column("Salary"),
- grid.Column("MobileNo", header: "Mobile"),
- grid.Column("Department", format: @<text>@item.Department.DeptName</text>),
- grid.Column("EmpDOB")));
- }
Now the page number style will look like the preceding.
Enable search in Webgrid
For searching the records in a webgrid we need to modify the view by adding a TextBox and button using the following code.
- @using (Html.BeginForm("EmpListUsingGrid", "Employees", FormMethod.Get))
- {
- <text >Employee Name</text>
- <input id="tbtEmployeeName" type="text" name="EmpName" />
- <input id="Submit1" type="submit" value="submit" />
- }
And modify the controller action method for that grid as follows.
- public ActionResult EmpListUsingGrid(string EmpName)
- {
- if (string.IsNullOrEmpty(EmpName))
- {
- return View(db.Employees.Include(e => e.Department).ToList());
- }
- else
- {
- return View(db.Employees.Include(e => e.Department)
- .Where(x => x.EmpName.StartsWith(EmpName)).ToList());
- }
- }
There is no change in the controller action method that we already discussed in a previous session. If you have any confusion then please go through that first.
The entire view code is:
- @model IEnumerable<CodeFirstApproachWithEmployeesInfo.Models.Employee>
-
- @{
- ViewBag.Title = "EmpListUsingGrid";
- }
-
- <h2>List of Employees in Web Grid</h2>
- @using (Html.BeginForm("EmpListUsingGrid", "Employees", FormMethod.Get))
- {
- <text>Employee Name</text>
- <input id="tbtEmployeeName" type="text" name="EmpName" />
- <input id="Submit1" type="submit" value="submit" />
- }
- @{
- var grid = new WebGrid(source: Model, canPage: true,rowsPerPage :3);
- @grid.GetHtml(tableStyle: "table", htmlAttributes: new { id = "DataTable" }, columns: grid.Columns(
- grid.Column("EmpName"),
- grid.Column("Gender"),
- grid.Column("EmailId"),
- grid.Column("Salary"),
- grid.Column("MobileNo", header: "Mobile"),
- grid.Column("Department", format: @<text>@item.Department.DeptName</text>),
- grid.Column("EmpDOB")));
- }
Add link inside web grid
For adding a link button inside the web grid we need to modify the grid with the following code.
- grid.Column("", header: "Action", format: @<text>@Html.ActionLink("Edit", "Edit", new { id = item.Id }, new { target = "_blank" })|
- @Html.ActionLink("Details", "Details", new { id = item.Id }) |
- @Html.ActionLink("Delete", "Delete", new { id = item.Id })</text>)));
The complete grid will be like:
- @model IEnumerable<CodeFirstApproachWithEmployeesInfo.Models.Employee>
-
- @{
- ViewBag.Title = "EmpListUsingGrid";
- }
-
- <h2>List Of Employees In Web Grid</h2>
- @using (Html.BeginForm("EmpListUsingGrid", "Employees", FormMethod.Get))
- {
- <text >Employee Name</text>
- <input id="tbtEmployeeName" type="text" name="EmpName" />
- <input id="Submit1" type="submit" value="submit" />
- }
- @{
- var grid = new WebGrid(source: Model, canPage: true,rowsPerPage :3);
- @grid.GetHtml(tableStyle: "table", htmlAttributes: new { id = "DataTable" }, columns: grid.Columns(
- grid.Column("EmpName"),
- grid.Column("Gender"),
- grid.Column("EmailId"),
- grid.Column("Salary"),
- grid.Column("MobileNo", header: "Mobile"),
- grid.Column("Department", format: @<text>@item.Department.DeptName</text>),
- grid.Column("EmpDOB")
- ,grid.Column("", header: "Action", format: @<text>@Html.ActionLink("Edit", "Edit", new { id = item.Id }, new { target = "_blank" })|
- @Html.ActionLink("Details", "Details", new { id = item.Id }) |
- @Html.ActionLink("Delete", "Delete", new { id = item.Id })</text>)));
- }
Run this view and get the following output:
Note: fillEmptyRows: true,
//show empty row when there is only one record on page to it will display all empty rows there.
Summary
In this illustration you came to understand the basics of web grid in MVC. Download the sample code for a better understanding.
Thanks.
I would like to get feedback from my readers. Please post your feedback, question, or comments about this article.