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 { getset; }    
  4.     public string Name { getset; }    
  5.     public string Phone { getset; }    
  6.     public string Address { getset; }    
  7.     public string Class { getset; }    
  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. <script type="text/javascript">    
  5.     $(document).ready(function () {    
  6.         $('#bttnSearch').click(function () {    
  7.             var stuName = $('#txtName').attr('value');    
  8.             $.ajax({    
  9.                 type: "post",    
  10.                 url: "/Student/StudentGrid",    
  11.                 data: { studentName: $('#txtName').attr('value') },    
  12.                 datatype: "json",    
  13.                 traditional: true,    
  14.                 success: function (data) {    
  15.                     // debugger    
  16.                     if (data == "No Record Found") {    
  17.                         alert('No Record Found');    
  18.                     }    
  19.                     else {    
  20.                         $('#gridContent').html(data);    
  21.                         $('#txtName').val(stuName);    
  22.                     }    
  23.                 }    
  24.             });    
  25.         });    
  26.     });    
  27. </script>    
  28.     
  29. <div id="grid">    
  30.     <table width="100%">    
  31.         <tr>    
  32.             <td>    
  33.                 <table>    
  34.                     <tr>    
  35.                         <td>    
  36.                             Name    
  37.                         </td>    
  38.                         <td>    
  39.                             <input type="text" id="txtName" />    
  40.                         </td>    
  41.                         <td>    
  42.                             <input type="button" id="bttnSearch" value="Search" />    
  43.                         </td>    
  44.                     </tr>    
  45.                 </table>    
  46.             </td>    
  47.         </tr>    
  48.         <tr>    
  49.             <td>    
  50.     
  51. @{    
  52.      var grid = new WebGrid(Model, canPage: true, rowsPerPage: 5,    
  53.      selectionFieldName: "selectedRow", ajaxUpdateContainerId: "gridContent");    
  54.      grid.Pager(WebGridPagerModes.All);  
  55. }    
  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>

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.     @grid.GetHtml(tableStyle: "webGrid",    
  6.     headerStyle: "header",    
  7.     alternatingRowStyle: "alt",    
  8.     selectedRowStyle: "select",    
  9.     columns: grid.Columns(    
  10.     grid.Column("Name"" Name"),    
  11.     grid.Column("Phone""Phone"),    
  12.     grid.Column("Address""Address"),    
  13.     grid.Column("Class""Class")    
  14. )) 
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
 


Similar Articles