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.
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
- Visual Studio 2012 / 2013 / 2015 / 2017
- Entity Framework 5 and above
- 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.
Next, we are going to create an ASP.NET MVC5 Web application.
Creating ASP.NET MVC5 Web Application
Open New Visual Studio 2015 IDE.
After opening IDE just, next we are going to create MVC project for doing that just click File - inside that New - Project.
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”.
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.
After clicking on OK button it will start to create a project.
Project Structure
After creating project, next, we are going to create Model.
Creating Customer Model
We are going to add Customer Model to the Models folder.
Code Snippet
- [Table("Customers")]
- public class Customers
- {
- [Key]
- public int? CustomerID { get; set; }
- [Required(ErrorMessage = "Required CompanyName")]
- public string CompanyName { get; set; }
- [Required(ErrorMessage = "Required ContactName")]
- public string ContactName { get; set; }
- [Required(ErrorMessage = "Required ContactTitle")]
- public string ContactTitle { get; set; }
- public string Address { get; set; }
-
- [Required(ErrorMessage = "Required City")]
- public string City { get; set; }
- public string Region { get; set; }
-
- [Required(ErrorMessage = "Required PostalCode")]
- public string PostalCode { get; set; }
-
- [Required(ErrorMessage = "Required Country")]
- public string Country { get; set; }
-
- [Required(ErrorMessage = "Required Phone")]
- public string Phone { get; set; }
- public string Fax { get; set; }
- }
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.
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
- using System.Data.Entity;
-
- namespace DemojTable.Models
- {
- public class DatabaseContext : DbContext
- {
- public DatabaseContext() : base("DBConnection")
- {
-
- }
- public DbSet<Customers> Customers { get; set; }
- }
- }
Connection string in Web.config file
- <connectionStrings>
- <addname="DBConnection"
- connectionString="Data Source=####; initial catalog=Northwind; user id=sa; password=Pass####;"
- providerName="System.Data.SqlClient" />
- </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”.
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
- Companyname – Will be used for searching company name
- jtStartIndex – page index of grid (1,2,3,4)
- jtPageSize – page size count (10,20,30,50,100)
- jtSorting – Sorting ascending or descending
Code Snippet
- [HttpPost]
- public JsonResult GetCustomers(string companyname = "", int jtStartIndex = 0, int jtPageSize = 0, string jtSorting = null)
- {
Next, in this action method, we are going to add 2 methods
- GetCustomerCount
In the GetCustomerCount method, it will get all count of customers from the table.
- 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
- public int GetCustomerCount()
- {
-
-
- using (var db = new DatabaseContext())
- {
- return db.Customers.Count();
- }
- }
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.
- public List<Customers> GetCustomersList(string companyname, int startIndex, int count, string sorting)
- {
-
- using (var db = new DatabaseContext())
- {
- IEnumerable<Customers> query = db.Customers;
-
-
- if (!string.IsNullOrEmpty(companyname))
- {
- query = query.Where(p => p.CompanyName.IndexOf(companyname, StringComparison.OrdinalIgnoreCase) >= 0);
- }
-
-
- if (string.IsNullOrEmpty(sorting) || sorting.Equals("CompanyName ASC"))
- {
- query = query.OrderBy(p => p.CompanyName);
- }
- else if (sorting.Equals("CompanyName DESC"))
- {
- query = query.OrderByDescending(p => p.CompanyName);
- }
- else if (sorting.Equals("ContactName ASC"))
- {
- query = query.OrderBy(p => p.ContactName);
- }
- else if (sorting.Equals("ContactName DESC"))
- {
- query = query.OrderByDescending(p => p.ContactName);
- }
- else if (sorting.Equals("Country ASC"))
- {
- query = query.OrderBy(p => p.Country);
- }
- else if (sorting.Equals("Country DESC"))
- {
- query = query.OrderByDescending(p => p.Country);
- }
- else if (sorting.Equals("City ASC"))
- {
- query = query.OrderBy(p => p.City);
- }
- else if (sorting.Equals("City DESC"))
- {
- query = query.OrderByDescending(p => p.City);
- }
- else
- {
- query = query.OrderBy(p => p.CustomerID);
- }
-
- return count > 0
- ? query.Skip(startIndex).Take(count).ToList()
- : query.ToList();
- }
- }
Understanding Code Snippet in steps.
- The first step we are going perform is creating instance of DatabaseContext
- In second step we are going to get IEnumerable of customer query
- 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
- 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).
- 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.
- [HttpPost]
- public JsonResult GetCustomers(string companyname = "", int jtStartIndex = 0, int jtPageSize = 0, string jtSorting = null)
- {
-
- var CustomerCount = GetCustomerCount();
- var Customer = GetCustomersList(companyname, jtStartIndex, jtPageSize, jtSorting);
- return Json(new { Result = "OK", Records = Customer, TotalRecordCount = CustomerCount });
- }
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.
Project structure after adding Index view.
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.
Project structure after adding jTable from NuGet
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.
- <!--Adding Theme for jTable Grid-->
- <!--You can choose any type of theme from the themes folder-->
- <link href="~/Content/bootstrap.css" rel="stylesheet" />
- <link href="~/Scripts/jtable/themes/metro/lightgray/jtable.css" rel="stylesheet" />
-
- <!--Adding jquery Plugin-->
- <script src="~/Scripts/jquery-1.10.2.js"></script>
- <script src="~/Scripts/jquery-ui-1.9.2.min.js"></script>
- <!--Adding jTable Plugin-->
- <script src="~/Scripts/jtable/jquery.jtable.min.js"></script>
-
- <!-- Import CSS file for validation engine (in Head section of HTML) -->
- <link href="~/Scripts/validationEngine/validationEngine.jquery.css" rel="stylesheet" type="text/css" />
-
- <!-- Import Javascript files for validation engine (in Head section of HTML) -->
- <script type="text/javascript" src="~/Scripts/validationEngine/jquery.validationEngine.js"></script>
- <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.
- <div class="container">
- <div class="col-md-12">
- <div id="CustomerTableContainer"></div>
- </div>
- </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
- <script>
- $(document).ready(function () {
- $('#CustomerTableContainer').jtable({
- title: 'Customers',
- paging: false,
- pageSize: 10,
- sorting: false,
- actions:
- {
- listAction: '/Demo/GetCustomers'
- },
- fields: {
- CustomerID: {
- key: true,
- list: false
- },
- CompanyName: {
- title: 'Company Name',
- width: '40%'
- },
- ContactName: {
- title: 'ContactName',
- width: '20%'
- },
- ContactTitle: {
- title: 'ContactTitle',
- width: '20%'
- },
- City: {
- title: 'City',
- width: '20%'
- },
- PostalCode: {
- title: 'PostalCode',
- width: '20%'
- },
- Country: {
- title: 'Country',
- width: '20%'
- },
- Phone: {
- title: 'Phone',
- width: '20%'
- }
- }
- });
-
- $('#CustomerTableContainer').jtable('load');
- });
-
- </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.
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
- paging: true,
- pageSize: 5,
-
- <script>
- $(document).ready(function () {
- $('#CustomerTableContainer').jtable({
- title: 'Customers',
- paging: true,
- pageSize: 5,
- sorting: false,
- actions:
- {
- listAction: '/Demo/GetCustomers'
- },
- fields: {
- CustomerID: {
- key: true,
- list: false
- },
- CompanyName: {
- title: 'Company Name',
- width: '40%'
- },
- ContactName: {
- title: 'ContactName',
- width: '20%'
- },
- ContactTitle: {
- title: 'ContactTitle',
- width: '20%'
- },
- City: {
- title: 'City',
- width: '20%'
- },
- PostalCode: {
- title: 'PostalCode',
- width: '20%'
- },
- Country: {
- title: 'Country',
- width: '20%'
- },
- Phone: {
- title: 'Phone',
- width: '20%'
- }
- }
- });
-
- $('#CustomerTableContainer').jtable('load');
- });
-
- </script>
Debugging view after I changed paging dropdown from 5 to 10.
Debugging view
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.
- <script>
- $(document).ready(function () {
- $('#CustomerTableContainer').jtable({
- title: 'Customers',
- paging: true,
- pageSize: 5,
- sorting: true,
- actions:
- {
- listAction: '/Demo/GetCustomers'
- },
- fields: {
- CustomerID: {
- key: true,
- list: false
- },
- CompanyName: {
- title: 'Company Name',
- width: '40%'
- },
- ContactName: {
- title: 'ContactName',
- width: '20%'
- },
- ContactTitle: {
- title: 'ContactTitle',
- width: '20%'
- },
- City: {
- title: 'City',
- width: '20%'
- },
- PostalCode: {
- title: 'PostalCode',
- width: '20%'
- },
- Country: {
- title: 'Country',
- width: '20%'
- },
- Phone: {
- title: 'Phone',
- width: '20%'
- }
- }
- });
-
- $('#CustomerTableContainer').jtable('load');
- });
-
- </script>
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
- [HttpPost]
- public JsonResult CreateCustomer([Bind(Exclude = "CustomerID")] Customers customers)
- {
- try
- {
-
- if (ModelState.IsValid)
- {
- using (var db = new DatabaseContext())
- {
-
- db.Customers.Add(customers);
- var data = db.SaveChanges();
- }
-
- return Json(new { Result = "OK", Record = customers });
- }
- else
- {
-
-
- StringBuilder msg = new StringBuilder();
-
- var errormessage = (from item in ModelState
- where item.Value.Errors.Any()
- select item.Value.Errors[0].ErrorMessage).ToList();
-
- for (int i = 0; i < errormessage.Count; i++)
- {
- msg.Append(errormessage[i].ToString());
- msg.Append("<br />");
- }
-
- return Json(new { Result = "Error occured", Message = msg.ToString() }, JsonRequestBehavior.AllowGet);
- }
- }
- catch (Exception ex)
- {
- return Json(new { Result = "Error occured", Message = ex.Message }, JsonRequestBehavior.AllowGet);
- }
-
- }
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
- actions:
- {
- listAction: '/Demo/GetCustomers',
- createAction: '/Demo/CreateCustomer'
- },
Complete Code Snippet
- <script>
- $(document).ready(function () {
- $('#CustomerTableContainer').jtable({
- title: 'Customers',
- paging: true,
- pageSize: 5,
- sorting: true,
- actions:
- {
- listAction: '/Demo/GetCustomers',
- createAction: '/Demo/CreateCustomer'
- },
- fields: {
- CustomerID: {
- key: true,
- list: false
- },
- CompanyName: {
- title: 'Company Name',
- width: '40%'
- },
- ContactName: {
- title: 'ContactName',
- width: '20%'
- },
- ContactTitle: {
- title: 'ContactTitle',
- width: '20%'
- },
- City: {
- title: 'City',
- width: '20%'
- },
- PostalCode: {
- title: 'PostalCode',
- width: '20%'
- },
- Country: {
- title: 'Country',
- width: '20%'
- },
- Phone: {
- title: 'Phone',
- width: '20%'
- }
- }
- });
-
- $('#CustomerTableContainer').jtable('load');
- });
-
- </script>
Now we have added “createAction” next 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.
Added custom jquery theme folder to project.
Adding custom jquery UI theme reference to view.
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.
Now if you click on Add new record button a new dialog will popup.
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.
-
- formCreated: function (event, data) {
- data.form.find('input[name="CompanyName"]').addClass('validate[required]');
- data.form.find('input[name="ContactName"]').addClass('validate[required]');
- data.form.find('input[name="ContactTitle"]').addClass('validate[required]');
- data.form.find('input[name="City"]').addClass('validate[required]');
- data.form.find('input[name="PostalCode"]').addClass('validate[required]');
- data.form.find('input[name="Country"]').addClass('validate[required]');
- data.form.find('input[name="Phone"]').addClass('validate[required]');
- data.form.validationEngine();
- },
-
- formSubmitting: function (event, data) {
- return data.form.validationEngine('validate');
- },
-
- formClosed: function (event, data) {
- data.form.validationEngine('hide');
- data.form.validationEngine('detach');
- }
Script and css to add for Validation to work
- <!-- Import CSS file for validation engine (in Head section of HTML) -->
- <link href="~/Scripts/validationEngine/validationEngine.jquery.css" rel="stylesheet" type="text/css" />
-
- <!-- Import Javascript files for validation engine (in Head section of HTML) -->
- <script type="text/javascript" src="~/Scripts/validationEngine/jquery.validationEngine.js"></script>
- <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
Now if we click on save button it will validate the form.
Let’s add some valid data to save details.
Adding New Customer
Debugging view
View after adding new customer
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
- public JsonResult EditCustomer(Customers customers)
- {
- try
- {
- if (ModelState.IsValid)
- {
- using (var db = new DatabaseContext())
- {
- db.Entry(customers).State = EntityState.Modified;
- db.SaveChanges();
- }
- return Json(new { Result = "OK" }, JsonRequestBehavior.AllowGet);
- }
- else
- {
- StringBuilder msg = new StringBuilder();
-
- var errorList = (from item in ModelState
- where item.Value.Errors.Any()
- select item.Value.Errors[0].ErrorMessage).ToList();
-
- return Json(new { Result = "ERROR", Message = errorList });
- }
- }
- catch (Exception ex)
- {
- return Json(new { Result = "ERROR", Message = ex.Message });
- }
- }
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
- actions:
- {
- listAction: '/Demo/GetCustomers',
- createAction: '/Demo/CreateCustomer',
- updateAction: '/Demo/EditCustomer'
- },
Complete Code Snippet
- <script>
- $(document).ready(function () {
- $('#CustomerTableContainer').jtable({
- title: 'Customers',
- paging: true,
- pageSize: 5,
- sorting: true,
- actions:
- {
- listAction: '/Demo/GetCustomers',
- createAction: '/Demo/CreateCustomer',
- updateAction: '/Demo/EditCustomer'
- },
- fields: {
- CustomerID: {
- key: true,
- list: false
- },
- CompanyName: {
- title: 'Company Name',
- width: '25%'
- },
- ContactName: {
- title: 'ContactName',
- width: '20%'
- },
- ContactTitle: {
- title: 'ContactTitle',
- width: '20%'
- },
- City: {
- title: 'City',
- width: '10%'
- },
- PostalCode: {
- title: 'PostalCode',
- width: '10%'
- },
- Country: {
- title: 'Country',
- width: '20%'
- },
- Phone: {
- title: 'Phone',
- width: '20%'
- }
- },
-
- formCreated: function (event, data) {
- data.form.find('input[name="CompanyName"]').addClass('validate[required]');
- data.form.find('input[name="ContactName"]').addClass('validate[required]');
- data.form.find('input[name="ContactTitle"]').addClass('validate[required]');
- data.form.find('input[name="City"]').addClass('validate[required]');
- data.form.find('input[name="PostalCode"]').addClass('validate[required]');
- data.form.find('input[name="Country"]').addClass('validate[required]');
- data.form.find('input[name="Phone"]').addClass('validate[required]');
- data.form.validationEngine();
- },
-
- formSubmitting: function (event, data) {
- return data.form.validationEngine('validate');
- },
-
- formClosed: function (event, data) {
- data.form.validationEngine('hide');
- data.form.validationEngine('detach');
- }
- });
-
-
-
- $('#CustomerTableContainer').jtable('load');
- });
-
- </script>
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.
Debugging view while updating data
After updating record, you can see the effect that the rows which we have updated is highlighted in below snapshot.
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
- public JsonResult DeleteCustomer(int CustomerID)
- {
- try
- {
- using (var db = new DatabaseContext())
- {
- Customers customer = db.Customers.Find(CustomerID);
- db.Customers.Remove(customer);
- db.SaveChanges();
- }
- return Json(new {Result = "OK" }, JsonRequestBehavior.AllowGet);
- }
- catch (Exception)
- {
- throw;
- }
- }
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
- actions:
- {
- listAction: '/Demo/GetCustomers',
- createAction: '/Demo/CreateCustomer',
- updateAction: '/Demo/EditCustomer',
- deleteAction: '/Demo/DeleteCustomer'
- },
Complete Code Snippet
- <script>
- $(document).ready(function () {
- $('#CustomerTableContainer').jtable({
- title: 'Customers',
- paging: true,
- pageSize: 5,
- sorting: true,
- actions:
- {
- listAction: '/Demo/GetCustomers',
- createAction: '/Demo/CreateCustomer',
- updateAction: '/Demo/EditCustomer',
- deleteAction: '/Demo/DeleteCustomer'
- },
- fields: {
- CustomerID: {
- key: true,
- list: false
- },
- CompanyName: {
- title: 'Company Name',
- width: '25%'
- },
- ContactName: {
- title: 'ContactName',
- width: '20%'
- },
- ContactTitle: {
- title: 'ContactTitle',
- width: '20%'
- },
- City: {
- title: 'City',
- width: '10%'
- },
- PostalCode: {
- title: 'PostalCode',
- width: '10%'
- },
- Country: {
- title: 'Country',
- width: '20%'
- },
- Phone: {
- title: 'Phone',
- width: '20%'
- }
- },
-
- formCreated: function (event, data) {
- data.form.find('input[name="CompanyName"]').addClass('validate[required]');
- data.form.find('input[name="ContactName"]').addClass('validate[required]');
- data.form.find('input[name="ContactTitle"]').addClass('validate[required]');
- data.form.find('input[name="City"]').addClass('validate[required]');
- data.form.find('input[name="PostalCode"]').addClass('validate[required]');
- data.form.find('input[name="Country"]').addClass('validate[required]');
- data.form.find('input[name="Phone"]').addClass('validate[required]');
- data.form.validationEngine();
- },
-
- formSubmitting: function (event, data) {
- return data.form.validationEngine('validate');
- },
-
- formClosed: function (event, data) {
- data.form.validationEngine('hide');
- data.form.validationEngine('detach');
- }
- });
-
- $('#CustomerTableContainer').jtable('load');
- });
-
- </script>
Grid with Delete button
Now if we click on delete button from grid a confirmation dialog will popup asking for confirmation to deleting data.
Confirmation before deleting data
Debugging view while Deleting data
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.
- <div class="filtering">
- <form>
- Company name: <input type="text" name="companyname" id="companyname" />
- <button type="submit" id="BtnSearch">Search</button>
- </form>
- </div>
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
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
-
- $('#BtnSearch').click(function (e) {
- e.preventDefault();
- $('#CustomerTableContainer').jtable('load', {
- companyname: $('#companyname').val()
- });
- });
Let’s save the application and run to see filtering of data example.
Filtering data with company name
Debugging View while Filtering data
Output after Filtering data
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.