Performing CRUD Operations Using jqGrid In ASP.NET MVC

Introduction

In this article we will create a very simple ASP.NET MVC application step by step. We will use code first approach of entity framework to generate the database and in that application we will use jqGrid and we will perform the CRUD operation using jqGrid. 
 
jqGrid Introduction

jqGrid is an AJAX enabled grid plugin for the java script which provides complete solutions for representing our data in the tabular format. This provides lots of features to manipulate data. Because it is a jQuery plugin it will work only on client side not on server side but for binding the data which will be on server side it can be loaded dynamically using ajax call. This is a free and open source library, which is distributed under MIT licence. 
 
Features of jqGrid
  • This works fines under IE, Chrome, Mozilla, Safari and Opera
  • This is CSS customizable with full Themeroller support
  • Its UI comes in 20+ languages
  • Supports Paging
  • Supports Sorting 
  • Supports Insertion, Edit, Deletion, Searching, Filtering
  • Inline Editing
  • AJAX enabled
  • Accepts XML/JSON/local array data sources
  • Import and Export Data
Example: This example will help you to perform CRUD operation using jqGrid in MVC. Follow the following steps:
 
1. Create a new MVC Project and give the name for your project. To create a new MVC project, Click File > New > Project or press CTRL + SHIFT + N.

 
 
2. Select MVC as a project Template with Individual Authentication.

 
 
3. Now for creating the table into the database using Code First Approach, I am creating a folder with name "Entities". For creating the folder inside the project right click on the folder and click on Add then click on New Folder.

 
 
Now give the name for the folder as "Entities".
 
4. Add a class inside Entities folder with Name "StudentMaster.cs". You can follow the below figure to add class:

 

Now one dialog box will be open give the name for that class as "StudentMaster.cs".

 
 
5. Now write the following code into "StudentMaster".
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel.DataAnnotations;  
  4. using System.Linq;  
  5. using System.Web;  
  6.   
  7. namespace StudentInformation.Entities  
  8. {  
  9.     public class StudentMaster  
  10.     {  
  11.         [Key]  
  12.         public string ID { getset; }  
  13.         [Required]  
  14.         public string Name { getset; }  
  15.         [Required]  
  16.         public string FatherName { getset; }  
  17.         [Required]  
  18.         public string Gender { getset; }  
  19.         [Required]  
  20.         public string ClassName { getset; }  
  21.         [Required]  
  22.         public DateTime DateOfAdmission { getset; }  
  23.     }  
  24. }  
6. Attach this entity to the entity framework. Go to the Models folder and Open "IdentityModels.cs" File add this StudentMaster Table to entity framework using the following code.
  1. public DbSet<StudentMaster> Students { getset; }  
Complete code of IdentityModels.cs,
  1. using Microsoft.AspNet.Identity.EntityFramework;  
  2. using StudentInformation.Entities;  
  3. using System.Data.Entity;  
  4.   
  5. namespace StudentInformation.Models  
  6. {  
  7.     // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.  
  8.     public class ApplicationUser : IdentityUser  
  9.     {  
  10.     }  
  11.   
  12.     public class ApplicationDbContext : IdentityDbContext<ApplicationUser>  
  13.     {  
  14.         public ApplicationDbContext()  
  15.             : base("DefaultConnection")  
  16.         {  
  17.         }  
  18.         public DbSet<StudentMaster> Students { getset; }  
  19.     }  
  20. }  
7. Now open Package Manager Console. You can open Package Manager Console using menu, Tools, then Library Package Manager, Package Manager Console,

 
 
8. Now Enable Migrations for the project by using the following code in package manager console:
  1. PM> Enable-Migrations  
9. After enabling migrations you will get one new folder inside your project with name Migrations where you will get Configuration.cs file.

 

10. Open Configuration.cs file and set AutomaticMigrationsEnabled as true.

 
11. Now build your project once and again open Package Manager Console and write the following code to generate tables and database.
  1. PM> update-database  
12. After writing above code you can open your server explorer (By pressing CTRL + ALT + S) and can see your table StudentMaster with fields which we have entered inside StudentMasters class.

 
 
13. Now add Controller with name "StudentController". To add controller in your project right click on Controllers  folder, Add, then Controller. Here's the figure to add StudentController.

 
 
Now add Empty Controller.

 

Now give the name for the controller.

 
 
14. Now Install jqGrid Package from the Nuget Package Manager. To add jqGrid package from the Nuget package Manager,
  • Right Click on the References and click on Manage Nuget Packages.
  • Now search for jqGrid and install jQuery.jqGrid.
 
15. Now open StudentController and add View by right clicking Index Action Method. 

 
16. Above operation will generate view, write the following code in that view.
  1. @{  
  2.     ViewBag.Title = "Student Information";  
  3. }  
  4.   
  5. <h2>Student Information</h2>  
  6. <div>  
  7.     <table id="jqGrid"></table>  
  8.     <div id="jqControls"></div>  
  9. </div>  
17. Add JavaScript file inside Scripts folder with name "Script.js".

 
 
Give the name for the file "script".
 
 

18. Now open StudentController and write the following code for getting the student information:
  1. public JsonResult GetStudents(string sidx, string sort, int page, int rows)  
  2.         {  
  3.             ApplicationDbContext db = new ApplicationDbContext();  
  4.             sort = (sort == null) ? "" : sort;  
  5.             int pageIndex = Convert.ToInt32(page) - 1;  
  6.             int pageSize = rows;  
  7.   
  8.             var StudentList = db.Students.Select(  
  9.                     t => new  
  10.                     {  
  11.                         t.ID,  
  12.                         t.Name,  
  13.                         t.FatherName,  
  14.                         t.Gender,  
  15.                         t.ClassName,  
  16.                         t.DateOfAdmission  
  17.                     });  
  18.             int totalRecords = StudentList.Count();  
  19.             var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);  
  20.             if (sort.ToUpper() == "DESC")  
  21.             {  
  22.                 StudentList = StudentList.OrderByDescending(t => t.Name);  
  23.                 StudentList = StudentList.Skip(pageIndex * pageSize).Take(pageSize);  
  24.             }  
  25.             else  
  26.             {  
  27.                 StudentList = StudentList.OrderBy(t => t.Name);  
  28.                 StudentList = StudentList.Skip(pageIndex * pageSize).Take(pageSize);  
  29.             }  
  30.             var jsonData = new  
  31.             {  
  32.                 total = totalPages,  
  33.                 page,  
  34.                 records = totalRecords,  
  35.                 rows = StudentList  
  36.             };  
  37.             return Json(jsonData, JsonRequestBehavior.AllowGet);  
  38.         }  
19. Now inside script.js file write the following code: 
  1. $(function () {  
  2.     $("#jqGrid").jqGrid({  
  3.         url: "/Student/GetStudents",  
  4.         datatype: 'json',  
  5.         mtype: 'Get',  
  6.         colNames: ['ID''Student Name''Father Name''Gender''Class''Admission Date'],  
  7.         colModel: [  
  8.             { key: true, hidden: true, name: 'ID', index: 'ID', editable: true },  
  9.             { key: false, name: 'Name', index: 'Name', editable: true },  
  10.             { key: false, name: 'FatherName', index: 'FatherName', editable: true },  
  11.             { key: false, name: 'Gender', index: 'Gender', editable: true, edittype: 'select', editoptions: { value: { 'M''Male''F''Female''N''None' } } },  
  12.             { key: false, name: 'ClassName', index: 'ClassName', editable: true, edittype: 'select', editoptions: { value: { '1''1st Class''2''2nd Class''3''3rd Class''4''4th Class''5''5th Class' } } },  
  13.             { key: false, name: 'DateOfAdmission', index: 'DateOfAdmission', editable: true, formatter: 'date', formatoptions: { newformat: 'd/m/Y' } }],  
  14.         pager: jQuery('#jqControls'),  
  15.         rowNum: 10,  
  16.         rowList: [10, 20, 30, 40, 50],  
  17.         height: '100%',  
  18.         viewrecords: true,  
  19.         caption: 'Students Records',  
  20.         emptyrecords: 'No Students Records are Available to Display',  
  21.         jsonReader: {  
  22.             root: "rows",  
  23.             page: "page",  
  24.             total: "total",  
  25.             records: "records",  
  26.             repeatitems: false,  
  27.             Id: "0"  
  28.         },  
  29.         autowidth: true,  
  30.         multiselect: false  
  31.     });  
  32. });  
20. Now finally include some references to index.cshtml View of Student. 
  1. @{  
  2.     ViewBag.Title = "Student Information";  
  3. }  
  4.   
  5. <h2>Student Information</h2>  
  6. <div>  
  7.     <table id="jqGrid"></table>  
  8.     <div id="jqControls"></div>  
  9. </div>  
  10. @section scripts{  
  11.     <link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />  
  12.     <link href="~/Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />  
  13.     <script src="~/Scripts/jquery-ui-1.10.4.js"></script>  
  14.     <script src="~/Scripts/i18n/grid.locale-en.js"></script>  
  15.     <script src="~/Scripts/jquery.jqGrid.min.js"></script>  
  16.     <script src="~/Scripts/script.js"></script>  
  17. }  
21. After provide references once built your project and run your project using F5 key. And type following URL "http://localhost:25784/Student". You will get the following output:

Output: 

 
22. Let's flip to StudentController and write code for create, update and delete.
  • For Create
    1. [HttpPost]  
    2. public string Create([Bind(Exclude = "Id")] StudentMaster Model)  
    3. {  
    4.    ApplicationDbContext db = new ApplicationDbContext();  
    5.    string msg;  
    6.    try  
    7.    {  
    8.       if (ModelState.IsValid)  
    9.       {  
    10.          Model.ID = Guid.NewGuid().ToString();  
    11.          db.Students.Add(Model);  
    12.          db.SaveChanges();  
    13.          msg = "Saved Successfully";  
    14.       }  
    15.       else  
    16.       {  
    17.             msg = "Validation data not successfully";  
    18.       }  
    19.    }  
    20.    catch (Exception ex)  
    21.    {  
    22.       msg = "Error occured:" + ex.Message;  
    23.    }  
    24.    return msg;  
    25. }  
  • For Update
    1. public string Edit(StudentMaster Model)  
    2. {  
    3.     ApplicationDbContext db = new ApplicationDbContext();  
    4.     string msg;  
    5.     try  
    6.     {  
    7.         if (ModelState.IsValid)  
    8.         {  
    9.             db.Entry(Model).State = EntityState.Modified;  
    10.             db.SaveChanges();  
    11.             msg = "Saved Successfully";  
    12.         }  
    13.         else  
    14.         {  
    15.             msg = "Validation data not successfully";  
    16.         }  
    17.     }  
    18.     catch (Exception ex)  
    19.     {  
    20.         msg = "Error occured:" + ex.Message;  
    21.     }  
    22.     return msg;  
    23. }  
  • For Delete
    1. public string Delete(string Id)  
    2. {  
    3.     ApplicationDbContext db = new ApplicationDbContext();  
    4.     StudentMaster student = db.Students.Find(Id);  
    5.     db.Students.Remove(student);  
    6.     db.SaveChanges();  
    7.     return "Deleted successfully";  
    8. }  
23. After writing above action methods open script.js file and add functionality for Create, Update, Delete. 
 
script.js File 
  1. $(function () {  
  2.     $("#jqGrid").jqGrid({  
  3.         url: "/Student/GetStudents",  
  4.         datatype: 'json',  
  5.         mtype: 'Get',  
  6.         colNames: ['ID''Student Name''Father Name''Gender''Class''Admission Date'],  
  7.         colModel: [  
  8.             { key: true, hidden: true, name: 'ID', index: 'ID', editable: true },  
  9.             { key: false, name: 'Name', index: 'Name', editable: true },  
  10.             { key: false, name: 'FatherName', index: 'FatherName', editable: true },  
  11.             { key: false, name: 'Gender', index: 'Gender', editable: true, edittype: 'select', editoptions: { value: { 'M''Male''F''Female''N''None' } } },  
  12.             { key: false, name: 'ClassName', index: 'ClassName', editable: true, edittype: 'select', editoptions: { value: { '1''1st Class''2''2nd Class''3''3rd Class''4''4th Class''5''5th Class' } } },  
  13.             { key: false, name: 'DateOfAdmission', index: 'DateOfAdmission', editable: true, formatter: 'date', formatoptions: { newformat: 'd/m/Y' } }],  
  14.         pager: jQuery('#jqControls'),  
  15.         rowNum: 10,  
  16.         rowList: [10, 20, 30, 40, 50],  
  17.         height: '100%',  
  18.         viewrecords: true,  
  19.         caption: 'Students Records',  
  20.         emptyrecords: 'No Students Records are Available to Display',  
  21.         jsonReader: {  
  22.             root: "rows",  
  23.             page: "page",  
  24.             total: "total",  
  25.             records: "records",  
  26.             repeatitems: false,  
  27.             Id: "0"  
  28.         },  
  29.         autowidth: true,  
  30.         multiselect: false  
  31.     }).navGrid('#jqControls', { edit: true, add: true, del: true, search: false, refresh: true },  
  32.         {  
  33.             zIndex: 100,  
  34.             url: '/Student/Edit',  
  35.             closeOnEscape: true,  
  36.             closeAfterEdit: true,  
  37.             recreateForm: true,  
  38.             afterComplete: function (response) {  
  39.                 if (response.responseText) {  
  40.                     alert(response.responseText);  
  41.                 }  
  42.             }  
  43.         },  
  44.         {  
  45.             zIndex: 100,  
  46.             url: "/Student/Create",  
  47.             closeOnEscape: true,  
  48.             closeAfterAdd: true,  
  49.             afterComplete: function (response) {  
  50.                 if (response.responseText) {  
  51.                     alert(response.responseText);  
  52.                 }  
  53.             }  
  54.         },  
  55.         {  
  56.             zIndex: 100,  
  57.             url: "/Student/Delete",  
  58.             closeOnEscape: true,  
  59.             closeAfterDelete: true,  
  60.             recreateForm: true,  
  61.             msg: "Are you sure you want to delete Student... ? ",  
  62.             afterComplete: function (response) {  
  63.                 if (response.responseText) {  
  64.                     alert(response.responseText);  
  65.                 }  
  66.             }  
  67.         });  
  68. });  
24. Now finally run that project and see output.  

Output

 
When you click on Create Button

 
 
After Adding Students
 
Editing a Record: For Editing a record you have to select one row and click on Edit Button.

 
After Updating Record

 
Deleting Record: First of all select a row and press Delete button.

 
Pagination
 
When Row List Change
 
 When Collapse Button is pressed
 
Final Output:
You can download complete source code of the project from GitHub.
 
Read more articles on ASP.NET

Up Next
    Ebook Download
    View all
    Learn
    View all
    sourabhsomani.com