Using jqGrid With ASP.NET MVC

In this article, we are going to learn how to use jqGrid with ASP.NET MVC along with we are going to use Entity framework for accessing the database.

Download source code

Download

If you belong to a background of ASP.NET web forms, then there is grid view which we used most but in some scenarios, if the data was large, then it would use to break. However, in MVC, we do not have that kind of grid which has all readymade events but there is HTML helper which helps you to generate the HTML in Web grid. In that, we need to use different packages for handling paging of the grid, and also, we need to pass a strongly typed model to view for rendering the grid.

Now, if we want a Grid which is lighter and easy to use, in that grid, we can do paging, search, and create a new record, Edit record, delete record easily, then we are going to use it right.

jqGrid with ASP.NET

Let’s start with database part first.

Database Part

I have created a database with the name “Northwind” and in that, it has “Customers” table.

jqGrid with ASP.NET

Next, we are going to create an ASP.NET MVC5 Web application.

Creating ASP.NET MVC5 Web Application

Open New Visual Studio 2015 IDE.

jqGrid with ASP.NET

After opening IDE just, next we are going to create MVC project for doing that just click File - inside that New - Project.

jqGrid with ASP.NET

After choosing a project, a new dialog will pop up with the name “New Project”. In that, we are going to choose Visual C# Project Templates >> Web >> ASP.NET Web Application. Then, we are going to name the project as “DemoGrids”.

jqGrid with ASP.NET

After naming the project we are going click on OK button to create a project.

A new dialog will pop up for choosing templates for Creating “ASP.NET Web Application;” in that template, we are going to Create MVC application. That's why we are going to choose “MVC template” and next click on OK button to create a project.

jqGrid with ASP.NET

After clicking on OK button it will start to create a project.

Project Structure

jqGrid with ASP.NET

After creating project next we are going to create Model.

Creating Customer Model

We are going to add Customer Model to the Models folder.

jqGrid with ASP.NET

  1. [Table("Customers")]  
  2. public class Customers  
  3. {  
  4.     [Key]  
  5.     public int? CustomerID { get; set; }  
  6.     [Required(ErrorMessage = "Required CompanyName")]  
  7.     public string CompanyName { get; set; }  
  8.     [Required(ErrorMessage = "Required ContactName")]  
  9.     public string ContactName { get; set; }  
  10.     [Required(ErrorMessage = "Required ContactTitle")]  
  11.     public string ContactTitle { get; set; }  
  12.     public string Address { get; set; }  
  13.     [Required(ErrorMessage = "Required City")]  
  14.     public string City { get; set; }  
  15.     public string Region { get; set; }  
  16.     [Required(ErrorMessage = "Required PostalCode")]  
  17.     public string PostalCode { get; set; }  
  18.     [Required(ErrorMessage = "Required Country")]  
  19.     public string Country { get; set; }  
  20.     [Required(ErrorMessage = "Required Phone")]  
  21.     public string Phone { get; set; }  
  22.     public string Fax { get; set; }  
  23. }     

After adding model next we are going to use Entity framework for accessing database to doing that we need to setup DbContext class.

Note

What is DbContext?

DbContext is an important part of Entity Framework.

It is a bridge between your domain or entity classes and the database.

DbContext is the primary class that is responsible for interacting with data as an object.

Referenced from: - http://www.entityframeworktutorial.net/EntityFramework4.3/dbcontext-vs-objectcontext.aspx

Setting up DbContext Class

In this part, we are first going to create a class with name “DatabaseContext” and this class will be inheriting from “DbContext” class.

We are going create this class in Model Folder.

jqGrid with ASP.NET

Note

“DBConnection” is Connection string name.

Note

What is DBSet?

Referenced from: - http://www.entityframeworktutorial.net/EntityFramework4.3/dbsetclass.aspx

DBSet class represents an entity set that is used for creating, read, update, and delete operations. A generic version of DBSet (DbSet<TEntity>) can be used when the type of entity is not known at build time.

After adding “DatabaseContext” class next we are going to inherit this class with “DbContext” class.

After inheriting class next in constructor we are going to create a connection for doing that we need to pass connection string name to “DbContext” class, we are passing connection string name as DBConnection.

After passing connection string next we are going to declare DbSet in “DbContext” class which will help us to perform create, read, update, and delete operations.

Code Snippet

  1. using System.Data.Entity;  
  2.   
  3. namespace DemoGrids.Models  
  4. {  
  5.     public class DatabaseContext : DbContext  
  6.     {  
  7.         public DatabaseContext() : base("DBConnection")  
  8.         {  
  9.         }  
  10.   
  11.         public DbSet<Customers> Customers { get; set;}  
  12.     }  
  13. }  

Connection string in Web.config file

  1. <connectionStrings>  
  2.   <add name="DBConnection"   
  3.        connectionString="Data Source=####; initial catalog=Northwind; user id=sa; password=Pass####;"  
  4.        providerName="System.Data.SqlClient" />  
  5. </connectionStrings>  

After setting up DbContext class next we are going to add jQuery.jqGrid package from NuGet packages.

Adding jQuery.jqGrid from NuGet packages

For adding jQuery.jqGrid Reference from NuGet package just right click on the project a list will populate in that just choose Manage NuGet Packages a new dialog will popup of NuGet in that there is Browse option with search, just search jQuery.jqGrid and from search result choose “jQuery.jqGrid” package and click on Install button, this package will add CSS and jQuery files required for the jqGrid grid.

jqGrid with ASP.NET

After installing jqGrid below is project structure which shows jqGrid grid reference is added to Content and Scripts folder.

jqGrid with ASP.NET

Next, we are going to add a controller.

Adding DemoController

In this part, we are going to add a controller with a name as “Demo”.

jqGrid with ASP.NET

Next, after adding Controller, we are going to get a Default Action method with name Index, this View we are going add for displaying Grid, Along with that we need to add another Action Method for handling Ajax Get Request for Getting Data and binding it to Grid.

Adding Action Method GetCustomer

This Action Method will return a JSON object that is required for binding data to gird.

Adding GetCustomers Action Method which will take few parameters as input for handling (sorting, Paging, and searching in the grid).

  1. //Gets the to-do Lists.    
  2.  public JsonResult GetCustomers(string word, int page, int rows, string searchString)   
  3.  {  
  4.      //#1 Create Instance of DatabaseContext class for Accessing Database.  
  5.      using (DatabaseContext db = new DatabaseContext())  
  6.      {  
  7.          //#2 Setting Paging  
  8.          int pageIndex = Convert.ToInt32(page) - 1;  
  9.          int pageSize = rows;  
  10.   
  11.          //#3 Linq Query to Get Customer   
  12.          var Results = db.Customers.Select(  
  13.              a => new  
  14.              {  
  15.                  a.CustomerID,  
  16.                  a.CompanyName,  
  17.                  a.ContactName,  
  18.                  a.ContactTitle,  
  19.                  a.City,  
  20.                  a.PostalCode,  
  21.                  a.Country,  
  22.                  a.Phone,  
  23.              });  
  24.            
  25.          //#4 Get Total Row Count  
  26.          int totalRecords = Results.Count();  
  27.          var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);  
  28.   
  29.          //#5 Setting Sorting  
  30.          if (sord.ToUpper() == "DESC")  
  31.          {  
  32.              Results = Results.OrderByDescending(s => s.CustomerID);  
  33.              Results = Results.Skip(pageIndex * pageSize).Take(pageSize);  
  34.          }  
  35.          else  
  36.          {  
  37.              Results = Results.OrderBy(s => s.CustomerID);  
  38.              Results = Results.Skip(pageIndex * pageSize).Take(pageSize);  
  39.          }  
  40.          //#6 Setting Search  
  41.          if (!string.IsNullOrEmpty(searchString))  
  42.          {  
  43.              Results = Results.Where(m => m.Country == searchString);  
  44.          }  
  45.          //#7 Sending Json Object to View.  
  46.          var jsonData = new  
  47.          {  
  48.              total = totalPages,  
  49.              page,  
  50.              records = totalRecords,  
  51.              rows = Results  
  52.          };  
  53.          return Json(jsonData, JsonRequestBehavior.AllowGet);  
  54.      }  
  55.  }  

Understanding Code Snippet.

  1. The first step we are going to create Instance of DatabaseContext for accessing Database.
  2. Second step setting page index on bases of Parameter which we receive from the request.
  3. The third Step we are going write Linq Query for Getting Data from Database which we are going to store in Result variable it is in IQueryable form.
  4. Fourth step we are going to calculate Total Records and Total Pages which we need to send it to View.
  5. Fifth Step Setting Sorting Order.
  6. Six Step Setting Search for Grid.
  7. Final Step in this step we are going to Collect all variable and send them to View in JSON Format.

After adding and Understanding GetCustomer Action Method next we are going to add View for Index Action Method which was default created while creating Controller.

Adding Index View to Index Action Method

In this part, we are going to add Index View.

jqGrid with ASP.NET

Project structure after adding Index view.

jqGrid with ASP.NET

Next, we are going to add jqGrid Script and CSS reference to Index View.

Adding Script and CSS reference of jqGrid to Index View

In this step, we are going to add jqGrid Script and CSS reference to index view.

This script is added to project when we add jqGrid Grid from NuGet package.

  1. <link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />  
  2. <link href="~/Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />  
  3. <script src="~/Scripts/jquery-1.10.2.min.js"></script>  
  4. <script src="~/Scripts/jquery-ui-1.10.0.js"></script>  
  5. <script src="~/Scripts/i18n/grid.locale-en.js"></script>  
  6. <script src="~/Scripts/jquery.jqGrid.min.js"></script>  

Adding empty <table> element

After adding Scripts and Css next we need to add table element for reserve the place where the grid should be created.

  1. <table id="Demogrid"></table>  

Next step we are going to show simple grid with Customers columns in it.

Creating jqGrid

In this part, we are going to write a script to create JqGrid and to call Action Method “GetCustomers” to get data to bind to the grid.

Code Snippet

  1. <script>  
  2.         $(function () {  
  3.             debugger;  
  4.             $("#Demogrid").jqGrid  
  5.             ({  
  6.                 url: "/Demo/GetCustomers",  
  7.                 datatype: 'json',  
  8.                 mtype: 'Get',  
  9.                 //table header name  
  10.                 colNames: ['CustomerID''CompanyName''ContactName',   
  11. 'ContactTitle''City',  'PostalCode''Country''Phone'],  
  12.                 //colModel takes the data from controller and binds to grid  
  13.                 colModel: [  
  14.                 { name: "CustomerID" },  
  15.                 { name: "CompanyName" },  
  16.                 { name: "ContactName" },  
  17.                 { name: "ContactTitle" },  
  18.                 { name: "City" },  
  19.                 { name: "PostalCode" },  
  20.                 { name: "Country" },  
  21.                 { name: "Phone" }  
  22.                 ],  
  23.                 height: '100%',  
  24.                 rowNum: 10,    
  25.                 viewrecords: true,  
  26.                 caption: 'JQgrid DEMO',  
  27.                 emptyrecords: 'No records',  
  28.                 jsonReader:  
  29.                 {  
  30.                     root: "rows",  
  31.                     page: "page",  
  32.                     total: "total",  
  33.                     records: "records",  
  34.                     repeatitems: false,  
  35.                     Id: "0"  
  36.                 },  
  37.                 autowidth: true,  
  38.             });  
  39.         });  
  40.     </script>  

JqGrid options

Referenced from - http://www.trirand.com/jqgridwiki/doku.php?id=wiki:first_grid

Property Description
urlTells us where to get the data. Typically this is a server-side function with a connection to a database which returns the appropriate information to be filled into the Body layer in the grid
datatypeThis tells jqGrid the type of information being returned so it can construct the grid. In this case, we tell the grid that we expect XML data to be returned from the server, but other formats are possible. For a list of all available datatypes refer to API Methods
mtypeTells us how to make the Ajax call: either 'GET' or 'POST'. In this case, we will use the GET method to retrieve data from the server
colNamesAn array in which we place the names of the columns. This is the text that appears in the head of the grid (Header layer). The names are separated by commas
colModelAn array that describes the model of the columns. This is the most important part of the grid. Here I explain only the options used above. For the complete list of options see colModel API
name: The name of the column. This name does not have to be the name of the database table, but later we will see how we can use this when we have different data formats.
index: The name passed to the server on which to sort the data (note that we could pass column numbers instead). Typically this is the name (or names) of the database – this is server-side sorting, so what you pass depends on what your server expects to receive.
width: The width of the column, in pixels.
align: The alignment of the column.
sortable: Specifies if the data in the grid can be sorted on this column; if false, clicking on the header has no effect.
pagerDefines that we want to use a pager bar to navigate through the records. This must be a valid HTML element; in our example, we gave the div the id of “pager”, but any name is acceptable. Note that the Navigation layer (the “pager” div) can be positioned anywhere you want, determined by your HTML; in our example, we specified that the pager will appear after the Body layer.
rowNumSets how many records we want to view in the grid. This parameter is passed to the URL for use by the server routine retrieving the data
rowListAn array to construct a select box element in the pager in which we can change the number of the visible rows. When changed during the execution, this parameter replaces the rowNum parameter that is passed to the URL
sortnameSets the initial sorting column. Can be a name or number. This parameter is added to the URL for use by the server routine
viewrecordsDefines whether we want to display the number of total records from the query in the pager bar
captionSets the caption for the grid. If this parameter is not set the Caption layer will be not visible

After setting up a script for creating JqGrid next we are going to Save and Run the application to have the first look at grid how it looks.

Snapshot of JqGrid

jqGrid with ASP.NET

Adding Pager

Now above grid, we can see that we can see only 10 rows but we cannot see pager to this grid right let’s enable paging to this grid such that we can display large sets of data in it.

  1. Adding paging element <div> with id pager.
    1. <div id="pager"></div>  

After adding pager element to view next step we need to add to more options to JqGrid.

  1. pager: jQuery('#pager'),  
  2. rowList: [10, 20, 30, 40],  

Code Snippet

  1. <script>  
  2.         $(function () {  
  3.             debugger;  
  4.             $("#Demogrid").jqGrid  
  5.             ({  
  6.                 url: "/Demo/GetCustomers",  
  7.                 datatype: 'json',  
  8.                 mtype: 'Get',  
  9.                 //table header name  
  10.                 colNames: ['CustomerID''CompanyName''ContactName''ContactTitle''City''PostalCode''Country''Phone'],  
  11.                 //colModel takes the data from controller and binds to grid  
  12.                 colModel: [  
  13.                 { name: "CustomerID" },  
  14.                 { name: "CompanyName" },  
  15.                 { name: "ContactName" },  
  16.                 { name: "ContactTitle" },  
  17.                 { name: "City" },  
  18.                 { name: "PostalCode" },  
  19.                 { name: "Country" },  
  20.                 { name: "Phone" }  
  21.                 ],  
  22.                 height: '100%',  
  23.                 viewrecords: true,  
  24.                 caption: 'JQgrid DEMO',  
  25.                 emptyrecords: 'No records',  
  26.                 rowNum: 10,  
  27.   
  28.                 pager: jQuery('#pager'),  
  29.                 rowList: [10, 20, 30, 40],  
  30.   
  31.                 jsonReader:  
  32.                 {  
  33.                     root: "rows",  
  34.                     page: "page",  
  35.                     total: "total",  
  36.                     records: "records",  
  37.                     repeatitems: false,  
  38.                     Id: "0"  
  39.                 },  
  40.                 autowidth: true,  
  41.             });  
  42.         });  
  43.     </script>  

Snapshot of JqGrid

jqGrid with ASP.NET

Debugging view after I change paging dropdown from 10 to 20.

Debugging view

jqGrid with ASP.NET

Snapshot of JqGrid

jqGrid with ASP.NET

After adding paging next we need to add icons for creating a new customer, editing customer, delete customer and also we need to search for this grid.

Adding edit, create, delete and search icons to grid pager

In this part we are going to add create, edit delete and search icons to the pager of the grid, for doing this we need to unable just few options on the grid.

These options are easy to set because they understand only Boolean value either true or false.

If we want to show only add icon then just make {add: true} and to hide it just make {add: false}.

  1. .navGrid('#pager',  
  2. {  
  3.     edit: true,  
  4.     add: true,  
  5.     del: true,  
  6.     search: true,  
  7.     refresh: true,  
  8.     closeAfterSearch: true  
  9. }  

Code Snippet

  1. <script>  
  2.         $(function () {  
  3.             debugger;  
  4.             $("#Demogrid").jqGrid  
  5.             ({  
  6.                 url: "/Demo/GetCustomers",  
  7.                 datatype: 'json',  
  8.                 mtype: 'Get',  
  9.                 //table header name  
  10.                 colNames: ['CustomerID''CompanyName''ContactName''ContactTitle''City''PostalCode''Country''Phone'],  
  11.                 //colModel takes the data from controller and binds to grid  
  12.                 colModel: [  
  13.                 { name: "CustomerID" },  
  14.                 { name: "CompanyName" },  
  15.                 { name: "ContactName" },  
  16.                 { name: "ContactTitle" },  
  17.                 { name: "City" },  
  18.                 { name: "PostalCode" },  
  19.                 { name: "Country" },  
  20.                 { name: "Phone" }  
  21.                 ],  
  22.                 height: '100%',  
  23.                 viewrecords: true,  
  24.                 caption: 'JQgrid DEMO',  
  25.                 emptyrecords: 'No records',  
  26.                 rowNum: 10,  
  27.   
  28.                 pager: jQuery('#pager'),  
  29.                 rowList: [10, 20, 30, 40],  
  30.   
  31.                 jsonReader:  
  32.                 {  
  33.                     root: "rows",  
  34.                     page: "page",  
  35.                     total: "total",  
  36.                     records: "records",  
  37.                     repeatitems: false,  
  38.                     Id: "0"  
  39.                 },  
  40.                 autowidth: true,  
  41.             }).navGrid('#pager',  
  42.             {  
  43.                 edit: true,  
  44.                 add: true,  
  45.                 del: true,  
  46.                 search: true,  
  47.                 refresh: true,  
  48.                 closeAfterSearch: true  
  49.             });  
  50.         });  
  51.     </script>  

Snapshot of JqGrid

jqGrid with ASP.NET

After completing with adding icons now let’s work on how to add a new customer with JqGrid.

Adding new Customer

For adding new customer first we need to add action method which will handle create new customer request.

For doing that we are going to add new Action method with name “CreateCustomer” which will take Customer Model as an input parameter.

In this method we are first going on to validate data which we are going to receive from Ajax request if it is valid then we are going to save that data into the database with help of entity framework and finally, we are going return response to Ajax method. And if data is not valid then we going to read ModelState for errors and that error will be sent as a response to Ajax method.

Code Snippet

  1. [HttpPost]  
  2.     public JsonResult CreateCustomer([Bind(Exclude = "CustomerID")] Customers customers)  
  3.     {  
  4.         StringBuilder msg = new StringBuilder();  
  5.         try  
  6.         {  
  7.             if (ModelState.IsValid)  
  8.             {  
  9.                 using (DatabaseContext db = new DatabaseContext())  
  10.                 {  
  11.                     db.Customers.Add(customers);  
  12.                     db.SaveChanges();  
  13.                     return Json("Saved Successfully", JsonRequestBehavior.AllowGet);  
  14.                 }  
  15.             }  
  16.             else  
  17.             {  
  18.                 var errorList = (from item in ModelState  
  19.                                  where item.Value.Errors.Any()  
  20.                                  select item.Value.Errors[0].ErrorMessage).ToList();  
  21.   
  22.                 return Json(errorList, JsonRequestBehavior.AllowGet);  
  23.             }  
  24.         }  
  25.         catch (Exception ex)  
  26.         {  
  27.             var errormessage = "Error occured: " + ex.Message;  
  28.             return Json(errormessage, JsonRequestBehavior.AllowGet);  
  29.         }  
  30.   
  31.     }  

After adding new action method which will handle post request next we need to add options to jqGrid which will post this request with CreateCustomer action method.

Code Snippet of JqGrid for creating new customer

  1. {  
  2.     // add options  
  3.     zIndex: 100,  
  4.     url: "/Demo/CreateCustomer",  
  5.     closeOnEscape: true,  
  6.     closeAfterAdd: true,  
  7.     afterComplete: function (response) {  
  8.         if (response.responseJSON)  
  9.         {  
  10.             if (response.responseJSON == "Saved Successfully") {  
  11.                 alert("Saved Successfully");  
  12.             }  
  13.             else {  
  14.                 var message = "";  
  15.                 for (var i = 0; i < response.responseJSON.length; i++) {  
  16.                     message += response.responseJSON[i];  
  17.                     message += "\n";  
  18.                 }  
  19.             }  
  20.               
  21.         }  
  22.     }  
  23. }  

After adding this options we are not going to see create customer popup for creating a new customer for doing that we need to add {editable: true} to each colModel property.

Code Snippet of adding editable: true to colModel property

  1. colModel:   
  2. [  
  3.   
  4. { name: "CustomerID", editable: true },  
  5. {  
  6.     name: "CompanyName", editable: true  
  7. },  
  8. {  
  9.     name: 'ContactName', editable: true  
  10. },  
  11. {  
  12.     name: "ContactTitle", editable: true  
  13. },  
  14. {  
  15.     name: "City", editable: true  
  16. },  
  17. {  
  18.     name: "PostalCode", editable: true  
  19. },  
  20. {  
  21.     name: "Country", editable: true  
  22. },  
  23. {  
  24.     name: "Phone", editable: true  
  25. }  
  26. ],  

After setting editable options as true that columns are only going to be visible in add record popup.

Snapshot of JqGrid

jqGrid with ASP.NET

But we have not added any validation to this fields till now.

Let’s add Validation to this fields.

Adding Validation (Required)

The first thing we need to add is to make all fields mandatory.

For doing this we need to add an editrules option to colModel.

editrules: {required: true}

Note: - editrules

This option adds additional properties to the editable element and should be used in colModel. Mostly it is used to validate the user input before submitting the value(s) to the server.

Referenced from - http://www.trirand.com/jqgridwiki/doku.php?id=wiki:common_rules

  1. colModel: [  
  2. {  
  3.     name: "CustomerID", editable: true  
  4. },  
  5. {  
  6.     name: "CompanyName", editable: true, editrules: { required: true }  
  7. },  
  8. {  
  9.     name: 'ContactName', editable: true, editrules: { required: true }  
  10. },  
  11. {  
  12.     name: "ContactTitle", editable: true, editrules: { required: true }  
  13. },  
  14. {  
  15.     name: "City", editable: true, editrules: { required: true }  
  16. },  
  17. {  
  18.     name: "PostalCode", editable: true, editrules: { required: true }  
  19. },  
  20. {  
  21.     name: "Country", editable: true, editrules: { required: true }  
  22. },  
  23. {  
  24.     name: "Phone", editable: true, editrules: { required: true }  
  25. }  
  26. ],  

Snapshot of JqGrid

jqGrid with ASP.NET

After making all fields Mandatory next we need some validation such as a textbox should only accept integer value as input right for doing that we just need to add another option to that column.

Code Snippet

  1. {  
  2.      name: "PostalCode", editable: true, editrules: {required: true, number: true}  
  3. }  

jqGrid with ASP.NET

Referenced from - http://www.trirand.com/jqgridwiki/doku.php?id=wiki:common_rules

Below is the list of available options:

OptionTypeDescription
edithiddenbooleanThis option is valid only in form editing module. By default, the hidden fields are not editable. If the field is hidden in the grid and edithidden is set to true, the field can be edited when add or edit methods are called.
requiredboolean(true or false) if set to true, the value will be checked and if empty, an error message will be displayed.
numberboolean(true or false) if set to true, the value will be checked and if this is not a number, an error message will be displayed.
integerboolean(true or false) if set to true, the value will be checked and if this is not an integer, an error message will be displayed.
minValuenumber(integer)if set, the value will be checked and if the value is less than this, an error message will be displayed.
maxValuenumber(integer)if set, the value will be checked and if the value is more than this, an error message will be displayed.
emailbooleanif set to true, the value will be checked and if this is not valid e-mail, an error message will be displayed
urlbooleanif set to true, the value will be checked and if this is not valid url, an error message will be displayed
datebooleanif set to true a value from datefmt option is get (if not set ISO date is used) and the value will be checked and if this is not a valid date, an error message will be displayed
timebooleanif set to true, the value will be checked and if this is not a valid time, an error message will be displayed. Currently, we support only hh: mm format and optional am/pm at the end
custombooleanif set to true allow the definition of the custom checking rules via a custom function. See below
custom_funcfunctionthis function should be used when a custom option is set to true. Parameters passed to this function are the value, which should be checked and the name - the property from colModel. The function should return an array with the following parameters: first parameter - true or false. The value of true means that the checking is successful false otherwise; the second parameter has sense only if the first value is false and represent the error message which will be displayed to the user. Typically this can look like this [false,”Please enter valid value”]

After having a look at validation next we are finally going to create a new customer.

jqGrid with ASP.NET

After posting data below is a snapshot of values populated in the model.

Snapshot of JqGrid

jqGrid with ASP.NET

After completing with add new customer next we are going to Edit Customer.

Edit/Update Customer details

For editing records first, we need to add action method that will handle edit request.

In below code snippet we take customer model as input, after that we are going to validate Model and update values in the database.

If we fail to update then we are going to show the alert message.

Code Snippet

  1. public string EditCustomer(Customers customers)  
  2. {  
  3.     string msg;  
  4.     try  
  5.     {  
  6.         if (ModelState.IsValid)  
  7.         {  
  8.             using (DatabaseContext db = new DatabaseContext())  
  9.             {  
  10.                 db.Entry(customers).State = EntityState.Modified;  
  11.                 db.SaveChanges();  
  12.                 msg = "Saved Successfully";  
  13.             }  
  14.         }  
  15.         else  
  16.         {  
  17.             msg = "Some Validation ";  
  18.         }  
  19.     }  
  20.     catch (Exception ex)  
  21.     {  
  22.         msg = "Error occured:" + ex.Message;  
  23.     }  
  24.     return msg;  
  25. }  

Code Snippet

To enable edit/update option we need to add this piece of code to JqGrid.

  1. {  
  2.     // edit option  
  3.     zIndex: 100,  
  4.     url: '/Demo/EditCustomer',  
  5.     closeOnEscape: true,  
  6.     closeAfterEdit: true,  
  7.     recreateForm: true,  
  8.     afterComplete: function (response)  
  9.     {  
  10.         if (response.responseText)  
  11.         {  
  12.             alert(response.responseText);  
  13.         }  
  14.     }  
  15. },  

For updating and deleting data we need unique ID.

In jqGrid we can mark unique id by setting Key: true.

Code Snippet

  1. colModel: [  
  2. {  
  3.     name: 'CustomerID',  
  4.     editable: true,  
  5.     key: true,  
  6.     hidden: true  
  7. },  

To edit record first we need to select a row then we need to click on Edit Icon.

jqGrid with ASP.NET

After selecting a row and clicking on edit icon a popup will show with a record which you have chosen for editing.

In that, we are going to change phone number and click on submit button to update record, for updating data it is going to call EditCustomer Action Method.

jqGrid with ASP.NET

Below is debugging view while update Customer data.

Debugging view

jqGrid with ASP.NET

Output after updating data

jqGrid with ASP.NET

After completing with edit customer next we are going to delete the record.

Delete Customer

For deleting records first we need to add action method that will handle delete request.

Below is code snippet which will handle delete request which takes Id (CustomerID) as input.

  1. public string DeleteCustomer(int Id)  
  2. {  
  3.     using (DatabaseContext db = new DatabaseContext())  
  4.     {  
  5.         Customers customer = db.Customers.Find(Id);  
  6.         db.Customers.Remove(customer);  
  7.         db.SaveChanges();  
  8.         return "Deleted successfully";  
  9.     }  
  10. }  

To enable delete option we need to add this piece of code to JqGrid.

  1. {  
  2.     // delete option  
  3.     zIndex: 100,  
  4.     url: "/Demo/DeleteCustomer",  
  5.     closeOnEscape: true,  
  6.     closeAfterDelete: true,  
  7.     recreateForm: true,  
  8.     msg: "Are you sure you want to delete this Customer?",  
  9.     afterComplete: function (response) {  
  10.         if (response.responseText) {  
  11.             alert(response.responseText);  
  12.         }  
  13.     }  
  14. }  

In a similar way delete record first we need to select a row then we need to click on Delete Icon.

jqGrid with ASP.NET

Delete confirmation message

jqGrid with ASP.NET

If clicking on delete button it will call DeleteCustomer Action Method. For deleting we required unique id which is CustomerID which get populated as we click on delete button because we have set CustomerID column as Key in JqGrid.

Debugging view

jqGrid with ASP.NET

Acknowledgement after deleting record

jqGrid with ASP.NET

Finally most of the operation we have completed but still, one operation is pending is a search option.

Search Customer

To enable search first thing we need to do is enable search on the pager.

For doing that, we need to enable {search: true} in the pager.

Debugging view

  1. .navGrid('#pager',  
  2. {  
  3.     edit: true,  
  4.     add: true,  
  5.     del: true,  
  6.     search: true,  
  7.     refresh: true,  
  8.     closeAfterSearch: true  
  9. },  

After that, you enable this option you can see search icon in grid footer.

jqGrid with ASP.NET

But one issue here is that when you click on edit search it shows all columns names in the first dropdown list.

jqGrid with ASP.NET

But we want to search on particular columns right for doing that we need to set {search} option to every column if we want to enable search for that column then set {search: true} and to disable search then set {search: false}.

We are going enable search for only 2 columns [CompanyName, ContactName]

Code Snippet

  1. colModel: [  
  2. {  
  3.     name: 'CustomerID',  
  4.     editable: true,  
  5.     key: true,  
  6.     hidden: true,  
  7.     search: false  
  8. },  
  9. {  
  10.     name: "CompanyName", editable: true, editrules: { required: true }, search: true  
  11. },  
  12. {  
  13.     name: 'ContactName', editable: true, editrules: { required: true }, search: true  
  14. },  
  15. {  
  16.     name: "ContactTitle", editable: true, editrules: { required: true }, search: false  
  17. },  
  18. {  
  19.     name: "City", editable: true, editrules: { required: true }, search: false  
  20. },  
  21. {  
  22.     name: "PostalCode", editable: true, editrules: { required: true, number: true }, search: false  
  23. },  
  24. {  
  25.     name: "Country", editable: true, editrules: { required: true }, search: false  
  26. },  
  27. {  
  28.     name: "Phone", editable: true, editrules: { required: true }, search: false  
  29. }  
  30. ],  

jqGrid with ASP.NET

Next we are going to search record by CompanyName.

jqGrid with ASP.NET

When we search, then are going to call GetCustomers Action Method.

In GetCustomers Action Method there is searchString parameter which gets populated with data what we search.

Debugging GetCustomers Action Method

jqGrid with ASP.NET

jqGrid with ASP.NET

Finally, let’s see complete code of Index View.

Complete Code Snippet of Index View

  1. @{  
  2.     Layout = null;  
  3. }  
  4.   
  5. <!DOCTYPE html>  
  6.   
  7. <html>  
  8. <head>  
  9.     <meta name="viewport" content="width=device-width" />  
  10.     <title>Index</title>  
  11.     <link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />  
  12.     <link href="~/Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />  
  13.   
  14.     <script src="~/Scripts/jquery-1.10.2.min.js"></script>  
  15.     <script src="~/Scripts/jquery-ui-1.10.0.js"></script>  
  16.     <script src="~/Scripts/i18n/grid.locale-en.js"></script>  
  17.     <script src="~/Scripts/jquery.jqGrid.min.js"></script>  
  18.   
  19.     <script>  
  20.         $(function ()   
  21.         {  
  22.             $("#Demogrid").jqGrid  
  23.             ({  
  24.                 url: "/Demo/GetCustomers",  
  25.                 datatype: 'json',  
  26.                 mtype: 'Get',  
  27.                 //table header name  
  28.                 colNames: ['CustomerID''CompanyName''ContactName''ContactTitle''City''PostalCode''Country''Phone'],  
  29.                 //colModel takes the data from controller and binds to grid  
  30.                 colModel: [  
  31.                 {  
  32.                     name: 'CustomerID',  
  33.                     editable: true,  
  34.                     key: true,  
  35.                     hidden: true,  
  36.                     search: false  
  37.                 },  
  38.                 {  
  39.                     name: "CompanyName", editable: true, editrules: { required: true }, search: true  
  40.                 },  
  41.                 {  
  42.                     name: 'ContactName', editable: true, editrules: { required: true }, search: true  
  43.                 },  
  44.                 {  
  45.                     name: "ContactTitle", editable: true, editrules: { required: true }, search: false  
  46.                 },  
  47.                 {  
  48.                     name: "City", editable: true, editrules: { required: true }, search: false  
  49.                 },  
  50.                 {  
  51.                     name: "PostalCode", editable: true, editrules: { required: true, number: true }, search: false  
  52.                 },  
  53.                 {  
  54.                     name: "Country", editable: true, editrules: { required: true }, search: false  
  55.                 },  
  56.                 {  
  57.                     name: "Phone", editable: true, editrules: { required: true }, search: false  
  58.                 }  
  59.                 ],  
  60.                 height: '100%',  
  61.                 viewrecords: true,  
  62.                 caption: 'JQgrid DEMO',  
  63.                 emptyrecords: 'No records',  
  64.                 rowNum: 10,  
  65.   
  66.                 pager: jQuery('#pager'),  
  67.                 rowList: [10, 20, 30, 40],  
  68.   
  69.                 jsonReader:  
  70.                 {  
  71.                     root: "rows",  
  72.                     page: "page",  
  73.                     total: "total",  
  74.                     records: "records",  
  75.                     repeatitems: false,  
  76.                     Id: "0"  
  77.                 },  
  78.                 autowidth: true  
  79.             }).navGrid('#pager',  
  80.             {  
  81.                 edit: true,  
  82.                 add: true,  
  83.                 del: true,  
  84.                 search: true,  
  85.                 refresh: true,  
  86.                 closeAfterSearch: true  
  87.             },  
  88.             {  
  89.                 // edit option  
  90.                 zIndex: 100,  
  91.                 url: '/Demo/EditCustomer',  
  92.                 closeOnEscape: true,  
  93.                 closeAfterEdit: true,  
  94.                 recreateForm: true,  
  95.                 afterComplete: function (response)  
  96.                 {  
  97.                     if (response.responseText)  
  98.                     {  
  99.                         alert(response.responseText);  
  100.                     }  
  101.                 }  
  102.             },  
  103.             {  
  104.                 // add option  
  105.                 zIndex: 100,  
  106.                 url: "/Demo/CreateCustomer",  
  107.                 closeOnEscape: true,  
  108.                 closeAfterAdd: true,  
  109.                 afterComplete: function (response) {  
  110.                     if (response.responseJSON)  
  111.                     {  
  112.                         if (response.responseJSON == "Saved Successfully") {  
  113.                             alert("Saved Successfully");  
  114.                         }  
  115.                         else {  
  116.                             var message = "";  
  117.                             for (var i = 0; i < response.responseJSON.length; i++) {  
  118.                                 message += response.responseJSON[i];  
  119.                                 message += "\n";  
  120.                             }  
  121.                         }  
  122.                           
  123.                     }  
  124.                 }  
  125.             },  
  126.             {  
  127.                 // delete option  
  128.                 zIndex: 100,  
  129.                 url: "/Demo/DeleteCustomer",  
  130.                 closeOnEscape: true,  
  131.                 closeAfterDelete: true,  
  132.                 recreateForm: true,  
  133.                 msg: "Are you sure you want to delete this Customer?",  
  134.                 afterComplete: function (response) {  
  135.                     if (response.responseText) {  
  136.                         alert(response.responseText);  
  137.                     }  
  138.                 }  
  139.             }  
  140.   
  141.             );  
  142.         });  
  143.     </script>  
  144. </head>  
  145. <body>  
  146.     <div>  
  147.         <table id="Demogrid"></table>  
  148.         <div id="pager"></div>  
  149.     </div>  
  150. </body>  
  151. </html>  

Wow, finally we have completed how to using JqGrid with ASP.NET MVC.

Source code and database script is available for download.

Up Next
    Ebook Download
    View all
    Learn
    View all