WebGrid in ASP.Net MVC

Introduction

Reporting is the main feature currently in any software application. In webform development, we choose a GridView or Repeater. In classic ASP we develop HTML table elements. In ASP.NET MVC, the new concept begins WebGrid. WebGrid is lightweight for showing data in report format. As you know, MVC is all about Model View Controller, in this article we will learn how to create a WebGrid and search data and show it in a WebGrid with Entity Framework.

SearchGridForm

How to Create a WebGrid

First of all, we want to show some data in a grid. So we have a StudentMaster table.

StudentMasterTable

And based on the preceding table, we need to create a Model, so let's create StudentModel.cs.

StudentModel.cs

  1. public class StudentModel  
  2. {  
  3.     public int StudentId { getset; }  
  4.     public string Name { getset; }  
  5.     public string Phone { getset; }  
  6.     public string Address { getset; }  
  7.     public string Class { getset; }  
  8. }  
  • Now create a school.edmx file
  • Select Add New Item then select ADO.Net Entity Model 

SchoolEntityModel

  • Click the Add button.
  • Now click Next in the wizard and then Finish.
  • Add a new Controller
     

StudentController.cs

  1. using MvcDemoApplication.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7. using System.Web.UI.WebControls;  
  8. using System.IO;  
  9. using System.Web.UI;  
  10.   
  11. namespace MvcDemoApplication.Controllers  
  12. {  
  13.     public class StudentController : Controller  
  14.     {  
  15.         //    
  16.         // GET: /Student/    
  17.         SchoolEntities1 schoolEntity = new SchoolEntities1();  
  18.         public ActionResult StudentGrid()  
  19.         {  
  20.             List<StudentModel> lstStudentModel = new List<StudentModel>();  
  21.             List<StudentMaster> lstStudentMasters = schoolEntity.StudentMasters.Where(x => x.IsActive == true).ToList();  
  22.             lstStudentMasters.ForEach(x =>  
  23.             {  
  24.                 StudentModel stuModel = new StudentModel();  
  25.                 stuModel.Name = x.Name;  
  26.                 stuModel.Phone = x.Phone;  
  27.                 stuModel.Address = x.Address;  
  28.                 stuModel.Class = x.Class;  
  29.                 lstStudentModel.Add(stuModel);  
  30.             });  
  31.             return View(lstStudentModel);  
  32.         }  
  33.   
  34.         [HttpPost]  
  35.         public ActionResult StudentGrid(string studentName)  
  36.         {  
  37.             List<StudentModel> lstStudentModel = new List<StudentModel>();  
  38.             List<StudentMaster> lstStudentMasters = schoolEntity.StudentMasters.Where(x => x.Name.Contains(studentName)).ToList();  
  39.             lstStudentMasters.ForEach(x =>  
  40.             {  
  41.                 StudentModel stuModel = new StudentModel();  
  42.                 stuModel.Name = x.Name;  
  43.                 stuModel.Phone = x.Phone;  
  44.                 stuModel.Address = x.Address;  
  45.                 stuModel.Class = x.Class;  
  46.                 lstStudentModel.Add(stuModel);  
  47.             });  
  48.             if (lstStudentModel.Count > 0)  
  49.             {  
  50.                 return View(lstStudentModel);  
  51.             }  
  52.             else  
  53.             {  
  54.                 return Json("No Record Found");  
  55.             }  
  56.         }  
  57.     }  
  58. }  
  • Add the View StudentGrid.cshtml
  1. @{  
  2.     ViewBag.Title = "StudentGrid";  
  3. }  
  4. <script type="text/javascript">  
  5.   
  6. $(document).ready(function () {  
  7. $('#bttnSearch').click(function () {  
  8. var stuName = $('#txtName').attr('value');  
  9. $.ajax({  
  10. type: "post",  
  11. url: "/Student/StudentGrid",  
  12. data: { studentName: $('#txtName').attr('value') },  
  13. datatype: "json",  
  14. traditional: true,  
  15. success: function (data) {  
  16. // debugger  
  17. if (data == "No Record Found") {  
  18. alert('No Record Found');  
  19. }  
  20. else {  
  21. $('#gridContent').html(data);  
  22. $('#txtName').val(stuName);  
  23. }  
  24. }  
  25. });  
  26. });  
  27. });  
  28. </script>  
  29.   
  30. <div id="grid">  
  31.     <table width="100%">  
  32.         <tr>  
  33.             <td>  
  34.                 <table>  
  35.                     <tr>  
  36.                         <td>  
  37.                             Name  
  38.                         </td>  
  39.                         <td>  
  40.                             <input type="text" id="txtName" />  
  41.                         </td>  
  42.                         <td>  
  43.                             <input type="button" id="bttnSearch" value="Search" />  
  44.                         </td>  
  45.                     </tr>  
  46.                 </table>  
  47.             </td>  
  48.         </tr>  
  49.         <tr>  
  50.             <td>  
  51.   
  52.                 @{  
  53.                     var grid = new WebGrid(Model, canPage: true, rowsPerPage: 5,  
  54.                     selectionFieldName: "selectedRow", ajaxUpdateContainerId: "gridContent");  
  55.                     grid.Pager(WebGridPagerModes.All);}  
  56.   
  57.   
  58.                 @grid.GetHtml(tableStyle: "webGrid",  
  59. headerStyle: "header",  
  60. alternatingRowStyle: "alt",  
  61. selectedRowStyle: "select",  
  62. columns: grid.Columns(  
  63. grid.Column("Name", " Name"),  
  64. grid.Column("Phone", "Phone"),  
  65. grid.Column("Address", "Address"),  
  66. grid.Column("Class", "Class")  
  67. ))  
  68.   
  69.             </td>  
  70.         </tr>  
  71.     </table>  
  72. </div>    

Understanding the Code

StudentModel.cs

  1. public class StudentModel  
  2. {  
  3.     public int StudentId { get; set; }  
  4.     public string Name { get; set; }  
  5.     public string Phone { get; set; }  
  6.     public string Address { get; set; }  
  7.     public string Class { get; set; }  
  8. }  
As you saw code above, we have a studentmaster table and based on that table we create 5 properties for StudentModel.

StudentController.cs

  1. SchoolEntities1 schoolEntity = new SchoolEntities1();  
  2. public ActionResult StudentGrid()  
  3. {  
  4. List<studentmodel> lstStudentModel = new List<studentmodel>();  
  5.         List<studentmaster>  
  6.             lstStudentMasters = schoolEntity.StudentMasters.Where(x => x.IsActive == true).ToList();  
  7.             lstStudentMasters.ForEach(x =>  
  8.             {  
  9.             StudentModel stuModel = new StudentModel();  
  10.             stuModel.Name = x.Name;  
  11.             stuModel.Phone = x.Phone;  
  12.             stuModel.Address = x.Address;  
  13.             stuModel.Class = x.Class;  
  14.             lstStudentModel.Add(stuModel);  
  15.             });  
  16.   return View(lstStudentModel);  
  17.   }  
In the code above at the top line you can see that we added the line SchoolEntities1 schoolEntity = new SchoolEntities1();

That means, here we will create an object of SchoolEntities, that we create in the SchoolEntity.edmx file. This object has details of all tables, View and Stored Procedures of your database. In this article we are only using the StudentMaster table, for fetching the data.

  1. public ActionResult StudentGrid()    
  2. {    
  3.    List<StudentModel> lstStudentModel = new List<StudentModel>();    
  4.    List<StudentMaster> lstStudentMasters = schoolEntity.StudentMasters.Where(x => x.IsActive == true).ToList();    
  5.    lstStudentMasters.ForEach(x =>    
  6.    {    
  7.     StudentModel stuModel = new StudentModel();    
  8.     stuModel.Name = x.Name;    
  9.     stuModel.Phone = x.Phone;    
  10.     stuModel.Address = x.Address;    
  11.     stuModel.Class = x.Class;    
  12.     lstStudentModel.Add(stuModel);    
  13.     });    
  14. return View(lstStudentModel);    
  15. }    
The code above hasg a main ActionResult for the StudentGrid Page Method.
  1. List<StudentMaster> lstStudentMasters = schoolEntity.StudentMasters.Where(x => x.IsActive == true).ToList();  

Here we have a list object of StudentMaster and based on the List of StudentMaster objects, we are fetching data from the schoolEntites1 class object.

  1. lstStudentMasters.ForEach(x =>    
  2. {    
  3.   StudentModel stuModel = new StudentModel();    
  4.   stuModel.Name = x.Name;    
  5.   stuModel.Phone = x.Phone;    
  6.   stuModel.Address = x.Address;    
  7.   stuModel.Class = x.Class;    
  8.   lstStudentModel.Add(stuModel);    
  9. });    
  10. return View(lstStudentModel);    
And based on the List object of StudentMaster, we filled in some data into the StudentModel object.  
    1. public ActionResult StudentGrid(string studentName)  
    2. {  
    3.     List<StudentModel> lstStudentModel = new List<StudentModel>();  
    4.     List<StudentMaster> lstStudentMasters = schoolEntity.StudentMasters.Where(x => x.Name.Contains(studentName)).ToList();  
    5.     lstStudentMasters.ForEach(x =>  
    6.     {  
    7.         StudentModel stuModel = new StudentModel();  
    8.         stuModel.Name = x.Name;  
    9.         stuModel.Phone = x.Phone;  
    10.         stuModel.Address = x.Address;  
    11.         stuModel.Class = x.Class;  
    12.         lstStudentModel.Add(stuModel);  
    13.     });  
    14.     if (lstStudentModel.Count > 0)  
    15.     {  
    16.         return View(lstStudentModel);  
    17.     }  
    18.     else  
    19.     {  
    20.         return Json("No Record Found");  
    21.     }  
    22. }  

The code above is for a [HttpPost] type of ActionResult, when the user fills in the name into the TextBox and click on the Search button. That code comes into effect.

StudentGrid.cshtml

  1. @{  
  2.     ViewBag.Title = "StudentGrid";  
  3. }  
  4.   
  5.   
  6.   
  7. <script type="text/javascript">  
  8.     $(document).ready(function () {  
  9.         $('#bttnSearch').click(function () {  
  10.             var stuName = $('#txtName').attr('value');  
  11.             $.ajax({  
  12.                 type: "post",  
  13.                 url: "/Student/StudentGrid",  
  14.                 data: { studentName: $('#txtName').attr('value') },  
  15.                 datatype: "json",  
  16.                 traditional: true,  
  17.                 success: function (data) {  
  18.                     // debugger  
  19.                     if (data == "No Record Found") {  
  20.                         alert('No Record Found');  
  21.                     }  
  22.                     else {  
  23.                         $('#gridContent').html(data);  
  24.                         $('#txtName').val(stuName);  
  25.                     }  
  26.                 }  
  27.             });  
  28.         });  
  29.     });  
  30. </script>  
  31.   
  32. <div id="grid">  
  33.     <table width="100%">  
  34.         <tr>  
  35.             <td>  
  36.                 <table>  
  37.                     <tr>  
  38.                         <td>  
  39.                             Name  
  40.                         </td>  
  41.                         <td>  
  42.                             <input type="text" id="txtName" />  
  43.                         </td>  
  44.                         <td>  
  45.                             <input type="button" id="bttnSearch" value="Search" />  
  46.                         </td>  
  47.                     </tr>  
  48.                 </table>  
  49.             </td>  
  50.         </tr>  
  51.         <tr>  
  52.             <td>  
  53.   
  54. @{  
  55.      var grid = new WebGrid(Model, canPage: true, rowsPerPage: 5,  
  56.      selectionFieldName: "selectedRow", ajaxUpdateContainerId: "gridContent");  
  57.      grid.Pager(WebGridPagerModes.All);
  58. }  
  59.   
  60.   
  61. @grid.GetHtml(tableStyle: "webGrid",  
  62. headerStyle: "header",  
  63. alternatingRowStyle: "alt",  
  64. selectedRowStyle: "select",  
  65. columns: grid.Columns(  
  66. grid.Column("Name", " Name"),  
  67. grid.Column("Phone", "Phone"),  
  68. grid.Column("Address", "Address"),  
  69. grid.Column("Class", "Class")  
  70. ))  
  71.   
  72.             </td>  
  73.         </tr>  
  74.     </table>  
  75. </div>  

This code will show data in the WebGrid.

  1. @{  
  2.     var grid = new WebGrid(Model, canPage: true, rowsPerPage: 5,  
  3.     selectionFieldName: "selectedRow", ajaxUpdateContainerId: "gridContent");  
  4.     grid.Pager(WebGridPagerModes.All);}  
  5.   
  6.   
  7.     @grid.GetHtml(tableStyle: "webGrid",  
  8.     headerStyle: "header",  
  9.     alternatingRowStyle: "alt",  
  10.     selectedRowStyle: "select",  
  11.     columns: grid.Columns(  
  12.     grid.Column("Name", " Name"),  
  13.     grid.Column("Phone", "Phone"),  
  14.     grid.Column("Address", "Address"),  
  15.     grid.Column("Class", "Class")  
  16. ))  
You can see in the code above then we have a grid variable. In this variable, we put all the WebGrid related data. Like rowsPerPage, Paging true or not, Model details.

Here you can also that the properties of the CSS in HeaderStyle, AlternatingRowStyle, SelectedRowStyle are set.

That's it, press F5 and run your code.

StudentListGridForm
 
SearchResultForm