Using jTable Grid With ASP.NET MVC

In this article, we are going to learn how to use jTable Grid with ASP.NET MVC, and  along with that we are going to Use Entity framework for accessing the database.

Link to download Source Code.

ASP.NET

What is jTable

jTable is a jQuery plugin that is used to create AJAX based CRUD tables without coding HTML or Javascript. It has several features including:

Automatically creates HTML table and loads records from the server using AJAX.

Creates 'create new record' jQueryUI dialog form. When a user creates a record, it sends data to the server using AJAX and adds the same record to the table on the page.

Creates 'edit record' jQueryUI dialog form. When the user edits a record, it updates server using AJAX and updates all cells on the table on the page.

Allow the user to 'delete a record' by jQueryUI dialog based confirmation. When a user deletes a record, it deletes the record from the server using AJAX and deletes the record from the table on the page.

 

  • Shows animations for create/delete/edit operations on the table.
  • Supports server side paging using AJAX.
  • Supports server side sorting using AJAX.
  • Supports master/child tables.
  • Allows the user to select rows.
  • Allows the user to resize columns.
  • Allows the user to show/hide columns.
  • Exposes some events to enable validation of forms.
  • It can be localized easily.

All styling of table and forms are defined in a CSS file, so you can easily change the style of everything to use the plugin in your pages. The CSS file is well defined and commented.

  • It comes with pre-defined color themes.
  • It is not depended on any server-side technology.
  • It is platform independent and works on all common browsers.

 

Note

Referenced from :- http://www.jtable.org/

Pre prerequisite for Application

  1. Visual Studio 2012 / 2013 / 2015 / 2017
  2. Entity Framework 5 and above
  3. SQL Server 2008

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.

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.

ASP.NET

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

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 “DemojTable”.

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.

ASP.NET

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

Project Structure

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.

ASP.NET

Code Snippet

  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.   
  14.     [Required(ErrorMessage = "Required City")]  
  15.     public string City { get; set; }  
  16.     public string Region { get; set; }  
  17.   
  18.     [Required(ErrorMessage = "Required PostalCode")]  
  19.     public string PostalCode { get; set; }  
  20.   
  21.     [Required(ErrorMessage = "Required Country")]  
  22.     public string Country { get; set; }  
  23.   
  24.     [Required(ErrorMessage = "Required Phone")]  
  25.     public string Phone { get; set; }  
  26.     public string Fax { get; set; }  
  27. }  

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.

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 DemojTable.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. <addname="DBConnection"  
  3. connectionString="Data Source=####; initial catalog=Northwind; user id=sa; password=Pass####;"  
  4. providerName="System.Data.SqlClient" />  
  5. </connectionStrings>  

Next, we are going to add a controller.

Adding DemoController

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

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).

Below you can see GetCustomers Action Method which has 4 parameters below

  1. Companyname – Will be used for searching company name
  2. jtStartIndex – page index of grid (1,2,3,4)
  3. jtPageSize – page size count (10,20,30,50,100)
  4. jtSorting – Sorting ascending or descending

Code Snippet

  1. [HttpPost]//Gets the todo Lists.    
  2. public JsonResult GetCustomers(string companyname = ""int jtStartIndex = 0, int jtPageSize = 0, string jtSorting = null)  
  3.  {  

Next, in this action method, we are going to add 2 methods

  1. GetCustomerCount
    In the GetCustomerCount method, it will get all count of customers from the table.
  1. GetCustomersList(string companyname, int startIndex, int count, string sorting)
    In the GetCustomersList method, it will take a parameter of paging and sorting and search as input and it will return Customer List as output.

Code Snippet of GetCustomerCount

  1. public int GetCustomerCount()  
  2. {  
  3.     // Instance of DatabaseContext  
  4.     //Customers is DbSet and Table name in Database is Customers  
  5.     using (var db = new DatabaseContext())  
  6.     {  
  7.         return db.Customers.Count();  
  8.     }         
  9. }  

After adding GetCustomer Count next we are going to add GetCustomers List Method.

Code Snippet of GetCustomersList

In the GetCustomersList method, it will take a parameter of paging and sorting and search as input and it will return Customer List as output.

  1. public List<Customers> GetCustomersList(string companyname, int startIndex, int count, string sorting)  
  2.         {  
  3.             // Instance of DatabaseContext  
  4.             using (var db = new DatabaseContext())  
  5.             {  
  6.                 IEnumerable<Customers> query = db.Customers;  
  7.   
  8.                 //Search  
  9.                 if (!string.IsNullOrEmpty(companyname))  
  10.                 {  
  11.                     query = query.Where(p => p.CompanyName.IndexOf(companyname, StringComparison.OrdinalIgnoreCase) >= 0);  
  12.                 }  
  13.   
  14.                 //Sorting Ascending and Descending  
  15.                 if (string.IsNullOrEmpty(sorting) || sorting.Equals("CompanyName ASC"))  
  16.                 {  
  17.                     query = query.OrderBy(p => p.CompanyName);  
  18.                 }  
  19.                 else if (sorting.Equals("CompanyName DESC"))  
  20.                 {  
  21.                     query = query.OrderByDescending(p => p.CompanyName);  
  22.                 }  
  23.                 else if (sorting.Equals("ContactName ASC"))  
  24.                 {  
  25.                     query = query.OrderBy(p => p.ContactName);  
  26.                 }  
  27.                 else if (sorting.Equals("ContactName DESC"))  
  28.                 {  
  29.                     query = query.OrderByDescending(p => p.ContactName);  
  30.                 }  
  31.                 else if (sorting.Equals("Country ASC"))  
  32.                 {  
  33.                     query = query.OrderBy(p => p.Country);  
  34.                 }  
  35.                 else if (sorting.Equals("Country DESC"))  
  36.                 {  
  37.                     query = query.OrderByDescending(p => p.Country);  
  38.                 }  
  39.                 else if (sorting.Equals("City ASC"))  
  40.                 {  
  41.                     query = query.OrderBy(p => p.City);  
  42.                 }  
  43.                 else if (sorting.Equals("City DESC"))  
  44.                 {  
  45.                     query = query.OrderByDescending(p => p.City);  
  46.                 }  
  47.                 else  
  48.                 {  
  49.                     query = query.OrderBy(p => p.CustomerID); //Default!  
  50.                 }  
  51.   
  52.                 return count > 0  
  53.                            ? query.Skip(startIndex).Take(count).ToList()  //Paging  
  54.                            : query.ToList(); //No paging  
  55.             }  
  56.         }  

Understanding Code Snippet in steps.

  1. The first step we are going perform is creating instance of DatabaseContext
  2. In second step we are going to get IEnumerable of customer query
  3. In the third step we are going to see if Company name is not null then we are going append where clause of Company name to the Main
  4. In the fourth step, we are going to work on Sorting (ascending and descending) and this clause will also append to query according to column user has sorted. We have only taken 4 parameters for sorting (Company Name, Contact Name, Country, City).
  5. In the fifth step, we are applying paging according to page index and page size we have received as input.

After understanding code snippet next we will code complete code snippet of GetCustomer Action Method.

Code Snippet of GetCustomers Action Method

In this Action Method we are going call 2 Method and after that we are going to return Json objects in that first we are going to return Result, after that we are going to return list of customer and finally we are going to return Total Customer Count.

  1. [HttpPost]//Gets the todo Lists.    
  2.  public JsonResult GetCustomers(string companyname = ""int jtStartIndex = 0, int jtPageSize = 0, string jtSorting = null)  
  3.  {  
  4.   
  5.      var CustomerCount = GetCustomerCount();  
  6.      var Customer = GetCustomersList(companyname, jtStartIndex, jtPageSize, jtSorting);  
  7.      return Json(new { Result = "OK", Records = Customer, TotalRecordCount = CustomerCount });  
  8.  }  

Now we have added GetCustomers Action Method Next we are going to Add Index View.

Adding Index View to Index Action Method

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

ASP.NET

Project structure after adding Index view.

ASP.NET

Installing jTable Grid from NuGet

To install the package, just right click on the project (DemojTable) and then, select "Manage NuGet package". The below dialog of NuGet Package Manager will pop up. In the browse tab, there is a search box. Type “jTable” and just click on "Install" button to install.

ASP.NET

Project structure after adding jTable from NuGet

ASP.NET

After adding jTable from NuGet next we are going to add Script and CSS reference of jTable on index View.

Adding Script and CSS reference of JTable Grid to Index View

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

  1. <!--Adding Theme for jTable Grid-->  
  2. <!--You can choose any type of theme from the themes folder-->  
  3. <link href="~/Content/bootstrap.css" rel="stylesheet" />  
  4. <link href="~/Scripts/jtable/themes/metro/lightgray/jtable.css" rel="stylesheet" />  
  5.   
  6. <!--Adding jquery Plugin-->  
  7. <script src="~/Scripts/jquery-1.10.2.js"></script>  
  8. <script src="~/Scripts/jquery-ui-1.9.2.min.js"></script>  
  9. <!--Adding jTable Plugin-->  
  10. <script src="~/Scripts/jtable/jquery.jtable.min.js"></script>  
  11.   
  12. <!-- Import CSS file for validation engine (in Head section of HTML) -->  
  13. <link href="~/Scripts/validationEngine/validationEngine.jquery.css" rel="stylesheet" type="text/css" />  
  14.   
  15. <!-- Import Javascript files for validation engine (in Head section of HTML) -->  
  16. <script type="text/javascript" src="~/Scripts/validationEngine/jquery.validationEngine.js"></script>  
  17. <script type="text/javascript" src="~/Scripts/validationEngine/jquery.validationEngine-en.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. <div class="container">  
  2.     <div class="col-md-12">  
  3.         <div id="CustomerTableContainer"></div>  
  4.     </div>  
  5. </div>  

Creating JTable Grid

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

You can see below we have written script to display Jtable in that we have set Grid title to Customer after that we have set paging false means all rows are going to be displayed, further sorting is also set to false, the main parameter to set in this grid is actions, first thing in action we are going to add “List Action” and we are going to set parameter to it as URL of “GetCustomers” Action Method, “/Demo/GetCustomers”.

After that in fields, we are going set all fields which we want to display in the grid but all fields must be present in Model (Customer Model) then only will be bound to grid because at the end we are going send Json object of Customers.

Code Snippet

  1. <script>  
  2.      $(document).ready(function () {  
  3.          $('#CustomerTableContainer').jtable({  
  4.              title: 'Customers',  
  5.              paging: false,  
  6.              pageSize: 10,  
  7.              sorting: false,  
  8.              actions:  
  9.                  {  
  10.                      listAction: '/Demo/GetCustomers'  
  11.                  },  
  12.              fields: {  
  13.                  CustomerID: {  
  14.                      key: true,  
  15.                      list: false  
  16.                  },  
  17.                  CompanyName: {  
  18.                      title: 'Company Name',  
  19.                      width: '40%'  
  20.                  },  
  21.                  ContactName: {  
  22.                      title: 'ContactName',  
  23.                      width: '20%'  
  24.                  },  
  25.                  ContactTitle: {  
  26.                      title: 'ContactTitle',  
  27.                      width: '20%'  
  28.                  },  
  29.                  City: {  
  30.                      title: 'City',  
  31.                      width: '20%'  
  32.                  },  
  33.                  PostalCode: {  
  34.                      title: 'PostalCode',  
  35.                      width: '20%'  
  36.                  },  
  37.                  Country: {  
  38.                      title: 'Country',  
  39.                      width: '20%'  
  40.                  },  
  41.                  Phone: {  
  42.                      title: 'Phone',  
  43.                      width: '20%'  
  44.                  }  
  45.              }  
  46.          });  
  47.   
  48.          $('#CustomerTableContainer').jtable('load');  
  49.      });  
  50.   
  51.  </script>  

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

ASP.NET

Enabling Pager

To enable paging we need to set “paging: true” and display number of rows set “pageSize: 5” I have set it to 5 rows it can be more than that.

Code Snippet

  1. paging: true,  
  2. pageSize: 5,  
  3.   
  4. <script>  
  5.         $(document).ready(function () {  
  6.             $('#CustomerTableContainer').jtable({  
  7.                 title: 'Customers',  
  8.                 paging: true,  
  9.                 pageSize: 5,  
  10.                 sorting: false,  
  11.                 actions:  
  12.                     {  
  13.                         listAction: '/Demo/GetCustomers'  
  14.                     },  
  15.                 fields: {  
  16.                     CustomerID: {  
  17.                         key: true,  
  18.                         list: false  
  19.                     },  
  20.                     CompanyName: {  
  21.                         title: 'Company Name',  
  22.                         width: '40%'  
  23.                     },  
  24.                     ContactName: {  
  25.                         title: 'ContactName',  
  26.                         width: '20%'  
  27.                     },  
  28.                     ContactTitle: {  
  29.                         title: 'ContactTitle',  
  30.                         width: '20%'  
  31.                     },  
  32.                     City: {  
  33.                         title: 'City',  
  34.                         width: '20%'  
  35.                     },  
  36.                     PostalCode: {  
  37.                         title: 'PostalCode',  
  38.                         width: '20%'  
  39.                     },  
  40.                     Country: {  
  41.                         title: 'Country',  
  42.                         width: '20%'  
  43.                     },  
  44.                     Phone: {  
  45.                         title: 'Phone',  
  46.                         width: '20%'  
  47.                     }  
  48.                 }  
  49.             });  
  50.   
  51.             $('#CustomerTableContainer').jtable('load');  
  52.         });  
  53.   
  54.     </script>  

ASP.NET

Debugging view after I changed paging dropdown from 5 to 10.

Debugging view
ASP.NET

After adding paging next, we are going to work on sorting.

Enabling sorting

To enable sorting just set “sorting: true” in the grid. Because we have already written code for performing sorting in GetCustomer Action Method.

  1. <script>  
  2.         $(document).ready(function () {  
  3.             $('#CustomerTableContainer').jtable({  
  4.                 title: 'Customers',  
  5.                 paging: true,  
  6.                 pageSize: 5,  
  7.                 sorting: true,  
  8.                 actions:  
  9.                     {  
  10.                         listAction: '/Demo/GetCustomers'  
  11.                     },  
  12.                 fields: {  
  13.                     CustomerID: {  
  14.                         key: true,  
  15.                         list: false  
  16.                     },  
  17.                     CompanyName: {  
  18.                         title: 'Company Name',  
  19.                         width: '40%'  
  20.                     },  
  21.                     ContactName: {  
  22.                         title: 'ContactName',  
  23.                         width: '20%'  
  24.                     },  
  25.                     ContactTitle: {  
  26.                         title: 'ContactTitle',  
  27.                         width: '20%'  
  28.                     },  
  29.                     City: {  
  30.                         title: 'City',  
  31.                         width: '20%'  
  32.                     },  
  33.                     PostalCode: {  
  34.                         title: 'PostalCode',  
  35.                         width: '20%'  
  36.                     },  
  37.                     Country: {  
  38.                         title: 'Country',  
  39.                         width: '20%'  
  40.                     },  
  41.                     Phone: {  
  42.                         title: 'Phone',  
  43.                         width: '20%'  
  44.                     }  
  45.                 }  
  46.             });  
  47.   
  48.             $('#CustomerTableContainer').jtable('load');  
  49.         });  
  50.   
  51.     </script>  

ASP.NET

After completing with sorting next we are going to Create Form.

Creating Form for Adding New Customer

For creating new form first thing we are going to do in this part is creating new Action Method in Demo Controller with name “CreateCustomer” which will take Customers Model as input.

Next we are going to validate Model which we are going to take as input if it is valid then we are going to save that customer in database else we are going to generate error message string from Model state error which we have received and that error message string will be sent to ajax request to display to user.

Code Snippet

  1. [HttpPost]  
  2. public JsonResult CreateCustomer([Bind(Exclude = "CustomerID")] Customers customers)  
  3. {  
  4.     try  
  5.     {  
  6.         //validating Model state   
  7.         if (ModelState.IsValid)  
  8.         {  
  9.             using (var db = new DatabaseContext())  
  10.             {  
  11.                 // Saving Customer  
  12.                 db.Customers.Add(customers);  
  13.                 var data = db.SaveChanges();  
  14.             }  
  15.             // Sending Response to Ajax request  
  16.             return Json(new { Result = "OK", Record = customers });  
  17.         }  
  18.         else  
  19.         {  
  20.             // Generating Error Message string to send error response  
  21.   
  22.             StringBuilder msg = new StringBuilder();  
  23.   
  24.             var errormessage = (from item in ModelState  
  25.                                 where item.Value.Errors.Any()  
  26.                                 select item.Value.Errors[0].ErrorMessage).ToList();  
  27.   
  28.             for (int i = 0; i < errormessage.Count; i++)  
  29.             {  
  30.                 msg.Append(errormessage[i].ToString());  
  31.                 msg.Append("<br />");  
  32.             }  
  33.             // Sending Response to Ajax request  
  34.             return Json(new { Result = "Error occured", Message = msg.ToString() }, JsonRequestBehavior.AllowGet);  
  35.         }  
  36.     }  
  37.     catch (Exception ex)  
  38.     {  
  39.         return Json(new { Result = "Error occured", Message = ex.Message }, JsonRequestBehavior.AllowGet);  
  40.     }  
  41.   
  42. }  

Now we have added Create Customer Action Method, and next we are going to add new “createAction in the Jtable grid to handle create Customer request.

Implementing CreateAction

In Create Action option we need to add the path of “controller/action” of that controller and action method which will handle creating a  new customer request.

Code Snippet

  1. actions:  
  2. {  
  3.     listAction: '/Demo/GetCustomers',  
  4.     createAction: '/Demo/CreateCustomer'  
  5. },  

Complete Code Snippet

  1. <script>  
  2.         $(document).ready(function () {  
  3.             $('#CustomerTableContainer').jtable({  
  4.                 title: 'Customers',  
  5.                 paging: true,  
  6.                 pageSize: 5,  
  7.                 sorting: true,  
  8.                 actions:  
  9.                 {  
  10.                     listAction: '/Demo/GetCustomers',  
  11.                     createAction: '/Demo/CreateCustomer'  
  12.                 },  
  13.                 fields: {  
  14.                     CustomerID: {  
  15.                         key: true,  
  16.                         list: false  
  17.                     },  
  18.                     CompanyName: {  
  19.                         title: 'Company Name',  
  20.                         width: '40%'  
  21.                     },  
  22.                     ContactName: {  
  23.                         title: 'ContactName',  
  24.                         width: '20%'  
  25.                     },  
  26.                     ContactTitle: {  
  27.                         title: 'ContactTitle',  
  28.                         width: '20%'  
  29.                     },  
  30.                     City: {  
  31.                         title: 'City',  
  32.                         width: '20%'  
  33.                     },  
  34.                     PostalCode: {  
  35.                         title: 'PostalCode',  
  36.                         width: '20%'  
  37.                     },  
  38.                     Country: {  
  39.                         title: 'Country',  
  40.                         width: '20%'  
  41.                     },  
  42.                     Phone: {  
  43.                         title: 'Phone',  
  44.                         width: '20%'  
  45.                     }  
  46.                 }  
  47.             });  
  48.   
  49.             $('#CustomerTableContainer').jtable('load');  
  50.         });  
  51.   
  52.     </script>  

Now we have added “createActionnext for display form we need to add a Jquery UI library reference to the view.

Downloading and Adding Various themes reference

In Jtable you can add the various theme of jquery UI of your choice you just need to download these themes from http://jqueryui.com/themeroller/ site and add this folder to your project and reference theme CSS on the view.

ASP.NET

Added custom jquery theme folder to project.

ASP.NET

Adding custom jquery UI theme reference to view.

ASP.NET

Now we have added all scripts and CSS reference on view, if we are going to have a look on grid now we are going to see “Add New Record” button on top of grid.

ASP.NET

Now if you click on Add new record button a new dialog will popup.

ASP.NET

Wow, it's good but we have not added any client-side validation so far let’s add that too before creating a new customer.

Making all fields mandatory

In this part, we are going to add required validation to all fields which we are taking as an input and we are going to write this logic in “formCreated” event.

Complete Code Snippet

Note - data.form: Reference to the form element as jQuery selection.

In this part just we are providing the id of input and adding class validate[required] to it.

  1. //Initialize validation logic when a form is created  
  2.  formCreated: function (event, data) {  
  3.      data.form.find('input[name="CompanyName"]').addClass('validate[required]');  
  4.      data.form.find('input[name="ContactName"]').addClass('validate[required]');  
  5.      data.form.find('input[name="ContactTitle"]').addClass('validate[required]');  
  6.      data.form.find('input[name="City"]').addClass('validate[required]');  
  7.      data.form.find('input[name="PostalCode"]').addClass('validate[required]');  
  8.      data.form.find('input[name="Country"]').addClass('validate[required]');  
  9.      data.form.find('input[name="Phone"]').addClass('validate[required]');  
  10.      data.form.validationEngine();  
  11.  },  
  12.  //Validate form when it is being submitted  
  13.  formSubmitting: function (event, data) {  
  14.      return data.form.validationEngine('validate');  
  15.  },  
  16.  //Dispose validation logic when form is closed  
  17.  formClosed: function (event, data) {  
  18.      data.form.validationEngine('hide');  
  19.      data.form.validationEngine('detach');  
  20.  }  

Script and css to add for Validation to work

  1. <!-- Import CSS file for validation engine (in Head section of HTML) -->  
  2.     <link href="~/Scripts/validationEngine/validationEngine.jquery.css" rel="stylesheet" type="text/css" />  
  3.   
  4. <!-- Import Javascript files for validation engine (in Head section of HTML) -->  
  5.     <script type="text/javascript" src="~/Scripts/validationEngine/jquery.validationEngine.js"></script>  
  6.     <script type="text/javascript" src="~/Scripts/validationEngine/jquery.validationEngine-en.js"></script>  

Note - the validationEngine script is available in this project download this sample application.

Now we have added all validation script, CSS and validation logic let’s save and run application to check validation.

Validation

ASP.NET

Now if we click on save button it will validate the form.

Let’s add some valid data to save details.

Adding New Customer

ASP.NET

Debugging view

ASP.NET

View after adding new customer

ASP.NET

Now after adding new customer next we are going to edit a customer.

Edit Customer

In this part, we are going to edit customer data for doing this process we first need to add Action Method which will handle Edit request.

We are going to add “EditCustomer” Action Method which will take customer model as input.

For updating Customer data key thing we require is CustomerID on which we are going to update data.

Code Snippet

  1. public JsonResult EditCustomer(Customers customers)  
  2. {  
  3.     try  
  4.     {  
  5.         if (ModelState.IsValid)  
  6.         {  
  7.             using (var db = new DatabaseContext())  
  8.             {  
  9.                 db.Entry(customers).State = EntityState.Modified;  
  10.                 db.SaveChanges();  
  11.             }  
  12.             return Json(new { Result = "OK" }, JsonRequestBehavior.AllowGet);  
  13.         }  
  14.         else  
  15.         {  
  16.             StringBuilder msg = new StringBuilder();  
  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(new { Result = "ERROR", Message = errorList });  
  23.         }  
  24.     }  
  25.     catch (Exception ex)  
  26.     {  
  27.         return Json(new { Result = "ERROR", Message = ex.Message });  
  28.     }  
  29. }  

After adding action method next, we need to update actions in scripts there we need to add new action of edit customer in it.

Implementing updateAction

In update Action option we need to add the path of “controller/action” of that controller and action method which will handle edit new customer request.

After adding updateAction you will see the edit button in the grid.

Code Snippet

  1. actions:  
  2. {  
  3.     listAction: '/Demo/GetCustomers',  
  4.     createAction: '/Demo/CreateCustomer',  
  5.     updateAction: '/Demo/EditCustomer'  
  6. },  

Complete Code Snippet

  1. <script>  
  2.         $(document).ready(function () {  
  3.             $('#CustomerTableContainer').jtable({  
  4.                 title: 'Customers',  
  5.                 paging: true,  
  6.                 pageSize: 5,  
  7.                 sorting: true,  
  8.                 actions:  
  9.                 {  
  10.                     listAction: '/Demo/GetCustomers',  
  11.                     createAction: '/Demo/CreateCustomer',  
  12.                     updateAction: '/Demo/EditCustomer'  
  13.                 },  
  14.                 fields: {  
  15.                     CustomerID: {  
  16.                         key: true,  
  17.                         list: false  
  18.                     },  
  19.                     CompanyName: {  
  20.                         title: 'Company Name',  
  21.                         width: '25%'  
  22.                     },  
  23.                     ContactName: {  
  24.                         title: 'ContactName',  
  25.                         width: '20%'  
  26.                     },  
  27.                     ContactTitle: {  
  28.                         title: 'ContactTitle',  
  29.                         width: '20%'  
  30.                     },  
  31.                     City: {  
  32.                         title: 'City',  
  33.                         width: '10%'  
  34.                     },  
  35.                     PostalCode: {  
  36.                         title: 'PostalCode',  
  37.                         width: '10%'  
  38.                     },  
  39.                     Country: {  
  40.                         title: 'Country',  
  41.                         width: '20%'  
  42.                     },  
  43.                     Phone: {  
  44.                         title: 'Phone',  
  45.                         width: '20%'  
  46.                     }  
  47.                 },  
  48.                 //Initialize validation logic when a form is created  
  49.                 formCreated: function (event, data) {  
  50.                     data.form.find('input[name="CompanyName"]').addClass('validate[required]');  
  51.                     data.form.find('input[name="ContactName"]').addClass('validate[required]');  
  52.                     data.form.find('input[name="ContactTitle"]').addClass('validate[required]');  
  53.                     data.form.find('input[name="City"]').addClass('validate[required]');  
  54.                     data.form.find('input[name="PostalCode"]').addClass('validate[required]');  
  55.                     data.form.find('input[name="Country"]').addClass('validate[required]');  
  56.                     data.form.find('input[name="Phone"]').addClass('validate[required]');  
  57.                     data.form.validationEngine();  
  58.                 },  
  59.                 //Validate form when it is being submitted  
  60.                 formSubmitting: function (event, data) {  
  61.                     return data.form.validationEngine('validate');  
  62.                 },  
  63.                 //Dispose validation logic when form is closed  
  64.                 formClosed: function (event, data) {  
  65.                     data.form.validationEngine('hide');  
  66.                     data.form.validationEngine('detach');  
  67.                 }  
  68.             });  
  69.   
  70.   
  71.   
  72.             $('#CustomerTableContainer').jtable('load');  
  73.         });  
  74.   
  75.     </script>  

ASP.NET

Now you can see the edit button in the grid, next let’s Edit this record.

For editing record just click on edit button a dialog will pop up with the record you have chosen for editing.

ASP.NET

Debugging view while updating data

ASP.NET

After updating record, you can see the effect that the rows which we have updated is highlighted in below snapshot.

ASP.NET

Now we have completed with editing and updating data next we are going to work on deleting data.

Deleting Customer

In this part, we are going to Delete customer data for doing this process we first need to add Action Method which will handle Delete request.

We are going to add “DeleteCustomer” Action Method which will take CustomerID as input.

For Deleting Customer data key thing we require is CustomerID on which we are going to delete customer data.

Code Snippet

  1. public JsonResult DeleteCustomer(int CustomerID)  
  2. {  
  3.     try  
  4.     {  
  5.         using (var db = new DatabaseContext())  
  6.         {  
  7.             Customers customer = db.Customers.Find(CustomerID);  
  8.             db.Customers.Remove(customer);  
  9.             db.SaveChanges();  
  10.         }  
  11.         return Json(new {Result = "OK" }, JsonRequestBehavior.AllowGet);  
  12.     }  
  13.     catch (Exception)  
  14.     {  
  15.         throw;  
  16.     }  
  17. }  

After adding action method next, we need to update actions in scripts where we need to add new action of delete customer in it.

Implementing deleteAction

In delete Action option we need to add the path of “controller/action” of that controller and action method which will handle delete customer request.

After adding deleteAction you will see delete button in the grid.

Code Snippet

  1. actions:  
  2. {  
  3.     listAction: '/Demo/GetCustomers',  
  4.     createAction: '/Demo/CreateCustomer',  
  5.     updateAction: '/Demo/EditCustomer',  
  6.     deleteAction: '/Demo/DeleteCustomer'  
  7. },  

Complete Code Snippet

  1. <script>  
  2.         $(document).ready(function () {  
  3.             $('#CustomerTableContainer').jtable({  
  4.                 title: 'Customers',  
  5.                 paging: true,  
  6.                 pageSize: 5,  
  7.                 sorting: true,  
  8.                 actions:  
  9.                 {  
  10.                     listAction: '/Demo/GetCustomers',  
  11.                     createAction: '/Demo/CreateCustomer',  
  12.                     updateAction: '/Demo/EditCustomer',  
  13.                     deleteAction: '/Demo/DeleteCustomer'  
  14.                 },  
  15.                 fields: {  
  16.                     CustomerID: {  
  17.                         key: true,  
  18.                         list: false  
  19.                     },  
  20.                     CompanyName: {  
  21.                         title: 'Company Name',  
  22.                         width: '25%'  
  23.                     },  
  24.                     ContactName: {  
  25.                         title: 'ContactName',  
  26.                         width: '20%'  
  27.                     },  
  28.                     ContactTitle: {  
  29.                         title: 'ContactTitle',  
  30.                         width: '20%'  
  31.                     },  
  32.                     City: {  
  33.                         title: 'City',  
  34.                         width: '10%'  
  35.                     },  
  36.                     PostalCode: {  
  37.                         title: 'PostalCode',  
  38.                         width: '10%'  
  39.                     },  
  40.                     Country: {  
  41.                         title: 'Country',  
  42.                         width: '20%'  
  43.                     },  
  44.                     Phone: {  
  45.                         title: 'Phone',  
  46.                         width: '20%'  
  47.                     }  
  48.                 },  
  49.                 //Initialize validation logic when a form is created  
  50.                 formCreated: function (event, data) {  
  51.                     data.form.find('input[name="CompanyName"]').addClass('validate[required]');  
  52.                     data.form.find('input[name="ContactName"]').addClass('validate[required]');  
  53.                     data.form.find('input[name="ContactTitle"]').addClass('validate[required]');  
  54.                     data.form.find('input[name="City"]').addClass('validate[required]');  
  55.                     data.form.find('input[name="PostalCode"]').addClass('validate[required]');  
  56.                     data.form.find('input[name="Country"]').addClass('validate[required]');  
  57.                     data.form.find('input[name="Phone"]').addClass('validate[required]');  
  58.                     data.form.validationEngine();  
  59.                 },  
  60.                 //Validate form when it is being submitted  
  61.                 formSubmitting: function (event, data) {  
  62.                     return data.form.validationEngine('validate');  
  63.                 },  
  64.                 //Dispose validation logic when form is closed  
  65.                 formClosed: function (event, data) {  
  66.                     data.form.validationEngine('hide');  
  67.                     data.form.validationEngine('detach');  
  68.                 }  
  69.             });  
  70.   
  71.             $('#CustomerTableContainer').jtable('load');  
  72.         });  
  73.   
  74.     </script>  

Grid with Delete button

ASP.NET

Now if we click on delete button from grid a confirmation dialog will popup asking for confirmation to deleting data.

Confirmation before deleting data

ASP.NET

Debugging view while Deleting data

ASP.NET

Now we have completed with Deleting data next we are going to work on filtering data.

Filtering data

The last part of this grid is filtering data for doing that first we need to add additional controls on View from which we are taking input and then we are going to filter data.

For that, we are going to add only simple textbox which will take company name as input to filter data and search button.

  1. <div class="filtering">  
  2.     <form>  
  3.         Company name: <input type="text" name="companyname" id="companyname" />  
  4.         <button type="submit" id="BtnSearch">Search</button>  
  5.     </form>  
  6. </div>  

ASP.NET

After adding a markup to the view we do not require adding any new code because the same GetCustomer action method will handle filtering data request.

You can see in below snapshot we have added companyname parameter to GetCustomer action method at the start we do not need any modification in that.

GetCustomer action method snapshot

ASP.NET

We need to add some code in jquery to carry out filtering process.

In this part, on click of search button, we are going to pass companyname parameter to GetCustomer action method which will filter data according to the company name and bind data to the grid.

Code Snippet

  1. //Re-load records when user click ‘search’ button.  
  2.  $('#BtnSearch').click(function (e) {  
  3.      e.preventDefault();  
  4.      $('#CustomerTableContainer').jtable('load', {  
  5.          companyname: $('#companyname').val()  
  6.      });  
  7.  });  

Let’s save the application and run to see filtering of data example.

Filtering data with company name

ASP.NET

Debugging View while Filtering data

ASP.NET

Output after Filtering data

ASP.NET

In this part, I have only added a textbox to filter data in the same way you can add a dropdown list or radio button and pass data to filter.

Finally, we have learned how to used JTable Grid with ASP.NET MVC in step by step way. I hope you enjoyed this article and also start using this grid in real time projects.

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now