Implementing JqGrid in ASP.NET MVC

JqGrid

Jqgrid is nothing but a jQuery plugin. It is an Ajax enabled JavaScript control which provides solutions for representing and manipulating tabular data on the web.There are many plugins for jQuery to display in a table manner with client side controllers. But the good thing about Jqgrid is it is a completely open source plugin. We can use it for production without paying a single penny. Actually this plugin mainly targets the PHP as the backend. But, we can use  the ASP.NET MVC application also. There are many other plugins like Jqgrid.

  1. Bootstrap grid (latest one)
  2. Gurido grid
  3. Kendo Grid (closed source application)
    There are a number of plugins among those; jqgrid's performance is good.

Features of JqGrid

  1. JQGrid helps us to develop most browser compatible web pages and also supports cross browser support functionality.
  2. CSS based themes. Developers can change the grid skin by defining their own UI CSS framework. The new rendering engine has a 5-10 times faster loading speed then the previous one.
  3. Pagination functionality is present. So no need to retrieve all the data from the server.
  4. Sorting, Various data types and sub grid support functionality.
  5. Event handlers and User API.
  6. Formatter supports advanced formatting of the contents of the cell in the required format in the
    client side itself.
  7. Inline Editing: easy to update the cell contents in a particular row.
  8. Searching and filtering.
  9. We can import and export data

Implementing Jqgrid

Step 1: Create Visual Studio Application

  1. Open Visual Studio 2015.
  2. Create ASP.NET MVC web application.
  3. Choose MVC template from the predefined templates and click ok.

    template

Step 2: Add Jqgrid Resources to the Project

  1. Right click solution-->manage nuget packages-->In "Nuget package manager window" select the Jquery-Jqgrid and click install.

    install

  2. Now the required jqgrid resources are added to the project. You can see the  files in solution explorer,

    solution

  3. If there is no Entity framework 5.0.0 in your visual studio install it.

Step 3: Prepare Data Source for Jqgrid

  1. Right click App_Start-->Add-->New Item-->Select "Sql Database" from Data templates--> name it as Database.mdf.
  2. Click Add button then database is created.
  3. Now Add Create User table: goto server explorer-->expand data connections-->expand DatabaseEntities-->Tables-->Add New Table.

    Table

  4. Click update button--> click Update database on next window, then table is created.

  5. Model Class creation

    Right click models folder-->Add-->New Item -->ADO.NET Entity Data Model

  6. Select Model Components from Database.

    Model Components

  7. Choose database from dropdown. DataEntities.mdf and name the connection string below.

    database

  8. Select table,

    table

  9. Model classes are created in the .edmx file in the Models folder like this,

    Model

Step 4: Create controller

  1. Right click Controllers folder-->add-->Controller-->select empty controller template-->name it as JqgridController.

    JqgridController.cs
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Web;  
    5. using System.Web.Mvc;  
    6. namespace Jqgrid.Controllers  
    7. {  
    8.     public class JqgridController: Controller  
    9.     {  
    10.         // GET: Jqgrid  
    11.         public ActionResult Index()  
    12.         {  
    13.             return View();  
    14.         }  
    15.     }  
    16. }  
  2. Now right click Index action method and add view.

    Replace the view code with the following code. In this view we are adding the references to the library files also.
    1. @{  
    2. ViewBag.Title = "Todo List";  
    3. }  
    4.   
    5. <h2>Todo List</h2>  
    6. <div>  
    7.     <table id="grid"></table>  
    8.     <div id="pager"></div>  
    9. </div>  
    10. <link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />  
    11. <link href="~/Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />  
    12. <script src="~/Scripts/jquery-1.9.1.min.js"></script>  
    13. <script src="~/Scripts/jquery-ui-1.10.4.min.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/myjqgrid.js"></script>  

Step 5: Prepare JSON method to send data to Jqgrid

  1. Now Modify the JqgridController/Index method.
    1. using System;  
    2. using System.Data;  
    3. using System.Linq;  
    4. using System.Data.Entity;  
    5. using System.Web.Mvc;  
    6. using Jqgrid.Models;  
    7. namespace Jqgrid.Controllers  
    8. {  
    9.     public class JqgridController: Controller  
    10.     {  
    11.         public ActionResult Index()  
    12.         {  
    13.             return View();  
    14.         }  
    15.         DatabaseEntities1 db = new DatabaseEntities1();  
    16.         public JsonResult GetValues(string sidx, string sord, int page, int rows) //Gets the todo Lists.  
    17.             {  
    18.                 int pageIndex = Convert.ToInt32(page) - 1;  
    19.                 int pageSize = rows;  
    20.                 var Results = db.Users.Select(  
    21.                     a => new  
    22.                     {  
    23.                         a.Id,  
    24.                             a.Name,  
    25.                             a.Phone,  
    26.                             a.Address,  
    27.                             a.DOB,  
    28.                     });  
    29.                 int totalRecords = Results.Count();  
    30.                 var totalPages = (int) Math.Ceiling((float) totalRecords / (float) rows);  
    31.                 if (sord.ToUpper() == "DESC")  
    32.                 {  
    33.                     Results = Results.OrderByDescending(s => s.Id);  
    34.                     Results = Results.Skip(pageIndex * pageSize).Take(pageSize);  
    35.                 } else  
    36.                 {  
    37.                     Results = Results.OrderBy(s => s.Id);  
    38.                     Results = Results.Skip(pageIndex * pageSize).Take(pageSize);  
    39.                 }  
    40.                 var jsonData = new  
    41.                 {  
    42.                     total = totalPages,  
    43.                         page,  
    44.                         records = totalRecords,  
    45.                         rows = Results  
    46.                 };  
    47.                 return Json(jsonData, JsonRequestBehavior.AllowGet);  
    48.             }  
    49.   
    50.         // TODO:insert a new row to the grid logic here  
    51.         [HttpPost]  
    52.         public string Create([Bind(Exclude = "Id")] User obj)  
    53.         {  
    54.             string msg;  
    55.             try  
    56.             {  
    57.                 if (ModelState.IsValid)  
    58.                 {  
    59.                     db.Users.Add(obj);  
    60.                     db.SaveChanges();  
    61.                     msg = "Saved Successfully";  
    62.                 } else  
    63.                 {  
    64.                     msg = "Validation data not successfull";  
    65.                 }  
    66.             } catch (Exception ex)  
    67.             {  
    68.                 msg = "Error occured:" + ex.Message;  
    69.             }  
    70.             return msg;  
    71.         }  
    72.         public string Edit(User obj)  
    73.         {  
    74.             string msg;  
    75.             try  
    76.             {  
    77.                 if (ModelState.IsValid)  
    78.                 {  
    79.                     db.Entry(obj).State = EntityState.Modified;  
    80.                     db.SaveChanges();  
    81.                     msg = "Saved Successfully";  
    82.                 } else  
    83.                 {  
    84.                     msg = "Validation data not successfull";  
    85.                 }  
    86.             } catch (Exception ex)  
    87.             {  
    88.                 msg = "Error occured:" + ex.Message;  
    89.             }  
    90.             return msg;  
    91.         }  
    92.         public string Delete(int Id)  
    93.         {  
    94.             User list = db.Users.Find(Id);  
    95.             db.Users.Remove(list);  
    96.             db.SaveChanges();  
    97.             return "Deleted successfully";  
    98.         }  
    99.     }  
    100. }  
  2. Using GetValues Json method we are binding the db data to the jqgrid in the format of Json (javascript object notation).

  3. Here parameters sidx means serial index; sort variable for sorting order; page numbers is for pages; and row parameter takes the numbers rows in jqgrid.

  4. Finally we are binding data using json() method as a json object.

Step 6: Create script for Jqgrid

The javascript code format for jqgrid is as follows,

  1. Create myjqgrid.js
    1. $(function()  
    2.   {  
    3.     debugger;  
    4.     $("#grid").jqGrid  
    5.     ({  
    6.         url: "/Jqgrid/GetValues",  
    7.         datatype: 'json',  
    8.         mtype: 'Get',  
    9.         //table header name   
    10.         colNames: ['Id''Name''Phone''Address''DOB'],  
    11.         //colModel takes the data from controller and binds to grid   
    12.         colModel: [  
    13.           {  
    14.             key: true,  
    15.             hidden: true,  
    16.             name: 'Id',  
    17.             index: 'Id',  
    18.             editable: true  
    19.         }, {  
    20.             key: false,  
    21.             name: 'Name',  
    22.             index: 'Name',  
    23.             editable: true  
    24.         }, {  
    25.             key: false,  
    26.             name: 'Phone',  
    27.             index: 'Phone',  
    28.             editable: true  
    29.         }, {  
    30.             key: false,  
    31.             name: 'Address',  
    32.             index: 'Address',  
    33.             editable: true  
    34.         }, {  
    35.             key: false,  
    36.             name: 'DOB',  
    37.             index: 'DOB',  
    38.             editable: true,  
    39.             formatter: 'date',  
    40.             formatoptions: {  
    41.                 newformat: 'd/m/Y'  
    42.             }  
    43.         }],  
    44.   
    45.         pager: jQuery('#pager'),  
    46.         rowNum: 10,  
    47.         rowList: [10, 20, 30, 40],  
    48.         height: '100%',  
    49.         viewrecords: true,  
    50.         caption: 'Jq grid sample Application',  
    51.         emptyrecords: 'No records to display',  
    52.         jsonReader:   
    53.         {  
    54.             root: "rows",  
    55.             page: "page",  
    56.             total: "total",  
    57.             records: "records",  
    58.             repeatitems: false,  
    59.             Id: "0"  
    60.         },  
    61.         autowidth: true,  
    62.         multiselect: false  
    63.             //pager-you have to choose here what icons should appear at the bottom  
    64.             //like edit,create,delete icons  
    65.     }).navGrid('#pager',   
    66.     {  
    67.         edit: true,  
    68.         add: true,  
    69.         del: true,  
    70.         search: false,  
    71.         refresh: true  
    72.     }, {  
    73.         // edit options  
    74.         zIndex: 100,  
    75.         url: '/Jqgrid/Edit',  
    76.         closeOnEscape: true,  
    77.         closeAfterEdit: true,  
    78.         recreateForm: true,  
    79.         afterComplete: function(response) {  
    80.             if (response.responseText) {  
    81.                 alert(response.responseText);  
    82.             }  
    83.         }  
    84.     }, {  
    85.         // add options  
    86.         zIndex: 100,  
    87.         url: "/Jqgrid/Create",  
    88.         closeOnEscape: true,  
    89.         closeAfterAdd: true,  
    90.         afterComplete: function(response) {  
    91.             if (response.responseText) {  
    92.                 alert(response.responseText);  
    93.             }  
    94.         }  
    95.     }, {  
    96.         // delete options  
    97.         zIndex: 100,  
    98.         url: "/Jqgrid/Delete",  
    99.         closeOnEscape: true,  
    100.         closeAfterDelete: true,  
    101.         recreateForm: true,  
    102.         msg: "Are you sure you want to delete this task?",  
    103.         afterComplete: function(response)  
    104.       {  
    105.             if (response.responseText)  
    106.             {  
    107.                 alert(response.responseText);  
    108.             }  
    109.         }  
    110.     });  
    111. });  

Now run the application:

Note

After running this if you did not get any grid display just go to _Layout.cshtml page which is present in Views/Shared folder .and just comment:

@Scripts.Render("~/bundles/jquery")

code

And change the route.config,

route.config

Final output of the application is: (I inserted some records in the User table),

output

Add you can also implement CRUD operations on Data.

ADD new record-->if you click the plus button on the below left corner then a popup will appear like this,

ADD new record

You can perform CRUD operations on Jqgrid without out postback like this because Jqgrid performs all operations through AJAX only.

Download sample code from Download. (Opens in visual studio 2015).

Conclusion

I hope you enjoyed the article. I always welcome any suggestions from you.See the original source of this article here Jqgrid implementation in mvc.

Up Next
    Ebook Download
    View all
    Learn
    View all