Practical Approach to Learn MVC: Part 6

This article provides a practical approach to learning MVC.

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:

  1. public ActionResult EmpListUsingGrid()  
  2. {   
  3.    return View(db.Employees.ToList());  
  4. }  
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.

add view

Step 3

Delete all the default code except following in that view.
  1. @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.
  1. <h2>List of Employees in Web Grid</h2>  
  2.   
  3. @{  
  4.     var grid = new WebGrid(source: Model);  
  5.     @grid.GetHtml(tableStyle: "table",columns: grid.Columns(  
  6.         grid.Column("EmpName"),  
  7.         grid.Column("Gender"),  
  8.         grid.Column("EmailId"),  
  9.         grid.Column("Salary"),  
  10.         grid.Column("MobileNo", header: "Mobile"),  
  11.                  grid.Column("Department", format: @<text>@item.Department.DeptName</text>),  
  12.                                    grid.Column("EmpDOB")));  
  13. }  

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:

  1. var grid = new WebGrid(source: Model,canPage :true,rowsPerPage:3);   
or alternatively:
  1. var grid = new WebGrid(source: Model,rowsPerPage:3);   
  2.   
  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:
  1. @model IEnumerable<CodeFirstApproachWithEmployeesInfo.Models.Employee>  
  2.   
  3. @{  
  4.     ViewBag.Title = "EmpListUsingGrid";  
  5.  }  
  6.   
  7. <h2>List Of Employees In Web Grid</h2>  
  8.   
  9. @{  
  10.     var grid = new WebGrid(source: Model, canPage: true);  
  11.     @grid.GetHtml(tableStyle: "table", htmlAttributes: new { id = "DataTable" }, columns: grid.Columns(  
  12.         grid.Column("EmpName"),  
  13.         grid.Column("Gender"),  
  14.         grid.Column("EmailId"),  
  15.                 grid.Column("Salary"),  
  16.         grid.Column("MobileNo", header: "Mobile"),  
  17.                  grid.Column("Department", format: @<text>@item.Department.DeptName</text>),  
  18.                                    grid.Column("EmpDOB")));  
  19. }  
Run the view and see the output like:

List Of Employees In Web

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:
  1. @model IEnumerable<CodeFirstApproachWithEmployeesInfo.Models.Employee>  
  2. <h2>List Of Employees In Web Grid</h2>  
  3. @{  
  4.     var grid = new WebGrid(source: Model, canPage: true, rowsPerPage: 2);  
  5.     @grid.GetHtml(tableStyle: "table",   
  6.     mode: WebGridPagerModes.All,  
  7.     //paging to grid  
  8.     firstText: "<< First",  
  9.     previousText: "< Previous ",  
  10.     nextText: "Next >",  
  11.     lastText: "Last >>",  
  12.     htmlAttributes: new { id = "DataTable" }, columns: grid.Columns(  
  13.     grid.Column("EmpName"),  
  14.     grid.Column("Gender"),  
  15.     grid.Column("EmailId"),  
  16.     grid.Column("Salary"),  
  17.     grid.Column("MobileNo", header: "Mobile"),  
  18.     grid.Column("Department", format: @<text>@item.Department.DeptName</text>),  
  19.                                             grid.Column("EmpDOB")));  
  20. }  
page number

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.
  1. @using (Html.BeginForm("EmpListUsingGrid""Employees", FormMethod.Get))  
  2. {  
  3.     <text >Employee Name</text>  
  4.     <input id="tbtEmployeeName" type="text" name="EmpName" />  
  5.     <input id="Submit1" type="submit" value="submit" />  
  6. }  
And modify the controller action method for that grid as follows.
  1. public ActionResult EmpListUsingGrid(string EmpName)  
  2. {  
  3.     if (string.IsNullOrEmpty(EmpName))  
  4.     {  
  5.         return View(db.Employees.Include(e => e.Department).ToList());  
  6.     }  
  7.     else  
  8.     {  
  9.         return View(db.Employees.Include(e => e.Department)  
  10.             .Where(x => x.EmpName.StartsWith(EmpName)).ToList());  
  11.     }    
  12. }  
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:
  1. @model IEnumerable<CodeFirstApproachWithEmployeesInfo.Models.Employee>  
  2.   
  3. @{  
  4.     ViewBag.Title = "EmpListUsingGrid";  
  5.  }  
  6.   
  7. <h2>List of Employees in Web Grid</h2>  
  8. @using (Html.BeginForm("EmpListUsingGrid""Employees", FormMethod.Get))  
  9. {  
  10.     <text>Employee Name</text>  
  11.     <input id="tbtEmployeeName" type="text" name="EmpName" />  
  12.     <input id="Submit1" type="submit" value="submit" />  
  13. }    
  14. @{  
  15.     var grid = new WebGrid(source: Model, canPage: true,rowsPerPage :3);  
  16.     @grid.GetHtml(tableStyle: "table", htmlAttributes: new { id = "DataTable" }, columns: grid.Columns(  
  17.         grid.Column("EmpName"),  
  18.         grid.Column("Gender"),  
  19.         grid.Column("EmailId"),  
  20.                 grid.Column("Salary"),  
  21.         grid.Column("MobileNo", header: "Mobile"),  
  22.                  grid.Column("Department", format: @<text>@item.Department.DeptName</text>),  
  23.                                    grid.Column("EmpDOB")));  
  24. }  
Add link inside web grid

For adding a link button inside the web grid we need to modify the grid with the following code.
  1. grid.Column("", header: "Action", format: @<text>@Html.ActionLink("Edit""Edit"new { id = item.Id }, new { target = "_blank" })|  
  2.     @Html.ActionLink("Details""Details"new { id = item.Id }) |  
  3.     @Html.ActionLink("Delete""Delete"new { id = item.Id })</text>)));  
The complete grid will be like:
  1. @model IEnumerable<CodeFirstApproachWithEmployeesInfo.Models.Employee>  
  2.   
  3. @{  
  4.     ViewBag.Title = "EmpListUsingGrid";  
  5.  }  
  6.   
  7. <h2>List Of Employees In Web Grid</h2>  
  8. @using (Html.BeginForm("EmpListUsingGrid""Employees", FormMethod.Get))  
  9. {  
  10.     <text >Employee Name</text>  
  11.     <input id="tbtEmployeeName" type="text" name="EmpName" />  
  12.     <input id="Submit1" type="submit" value="submit" />  
  13. }    
  14. @{  
  15. var grid = new WebGrid(source: Model, canPage: true,rowsPerPage :3);  
  16. @grid.GetHtml(tableStyle: "table", htmlAttributes: new { id = "DataTable" }, columns: grid.Columns(  
  17. grid.Column("EmpName"),  
  18. grid.Column("Gender"),  
  19. grid.Column("EmailId"),  
  20. grid.Column("Salary"),  
  21. grid.Column("MobileNo", header: "Mobile"),  
  22. grid.Column("Department", format: @<text>@item.Department.DeptName</text>),  
  23. grid.Column("EmpDOB")  
  24. ,grid.Column("", header: "Action", format: @<text>@Html.ActionLink("Edit""Edit"new { id = item.Id }, new { target = "_blank" })|  
  25. @Html.ActionLink("Details""Details"new { id = item.Id }) |  
  26. @Html.ActionLink("Delete""Delete"new { id = item.Id })</text>)));  
  27. }  
Run this view and get the following output:

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.