Using Gijgo Grid With ASP.NET MVC

Link to download Source code.

What is Gijgo?

Gijgo is a set of free open source JavaScript controls distributed under MIT License. All the widgets are high performance, built on top of the jQuery JavaScript library with built-in support for Bootstrap, Material Design, and Font Awesome. They are designed to save you time and scale with your development process.

ASP.NET

Using jqGrid with ASP.NET MVC

If you have heard about jqGrid and you want to use it, have a look at a detailed article of it. I am sure you will love it.

Prerequisites for application

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

Let’s start with the database part first.

Database Part

I have created a database with the name “Northwind” which 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, next, we are going to create MVC project. For doing that, just click File - 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 “DemoGijgo”.

ASP.NET

After naming the project, click on OK button to create the project. A new dialog will pop up for choosing templates for creating “ASP.NET Web Application;”. In that template, we are going to create an MVC application. That's why we are going to choose “MVC template” and next, click on OK button to create the project.

ASP.NET

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

Project Structure

ASP.NET

After creating project, create Model.

Creating Customer Model

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

ASP.NET

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

After adding model, we are going to use Entity framework for accessing the database. For that, we need to set up 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 the 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 to create this class in Models folder.

ASP.NET

Note

DBConnection” is Connection string name.

Note: - What is DBSet?

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 the class, in the constructor, we are going to create a connection. For doing that, we need to pass the connection string named as “DbContext” class. We are passing a connection string named as DBConnection.

After passing the connection string, 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 DemoGijgo.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 name “Demo”.

ASP.NET

Next, after adding Controller, we are going to get a Default Action method with name Index,  we are going add this View 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. public JsonResult GetCustomers(int? page, int? limit, string sortBy, string direction, string companyName, string contactName, string country)  
  2.         {  
  3.             List<Customers> records;  
  4.             int total;  
  5.             // step 1  
  6.             using (DatabaseContext context = new DatabaseContext())  
  7.             {  
  8.                 // step 2  
  9.                 var query = (from tempcustomer in context.Customers  
  10.                              select tempcustomer);  
  11.   
  12.                 // step 3 applying where clause to linq query if companyName is not empty  
  13.                 if (!string.IsNullOrWhiteSpace(companyName))  
  14.                 {  
  15.                     query = query.Where(q => q.CompanyName.Contains(companyName));  
  16.                 }  
  17.   
  18.                 // step 4 applying where clause to linq query if contactName is not empty  
  19.                 if (!string.IsNullOrWhiteSpace(contactName))  
  20.                 {  
  21.                     query = query.Where(q => q.ContactName != null && q.ContactName.Contains(contactName));  
  22.                 }  
  23.                 // step 5 applying where clause to linq query if country is not empty  
  24.                 if (!string.IsNullOrWhiteSpace(country))  
  25.                 {  
  26.                     query = query.Where(q => q.Country != null && q.Country.Contains(country));  
  27.                 }  
  28.   
  29.                 // step 6 applying sorting asc to (companyname,contactname,country,city)  
  30.   
  31.                 if (!string.IsNullOrEmpty(sortBy) && !string.IsNullOrEmpty(direction))  
  32.                 {  
  33.                     if (direction.Trim().ToLower() == "asc")  
  34.                     {  
  35.                         switch (sortBy.Trim().ToLower())  
  36.                         {  
  37.                             case "companyname":  
  38.                                 query = query.OrderBy(q => q.CompanyName);  
  39.                                 break;  
  40.                             case "contactname":  
  41.                                 query = query.OrderBy(q => q.ContactName);  
  42.                                 break;  
  43.                             case "country":  
  44.                                 query = query.OrderBy(q => q.Country);  
  45.                                 break;  
  46.                             case "city":  
  47.                                 query = query.OrderBy(q => q.City);  
  48.                                 break;  
  49.                         }  
  50.                     }  
  51.                     else  
  52.                     {  
  53.                         // step 7 applying sorting desc (companyname,contactname,country,city)  
  54.   
  55.                         switch (sortBy.Trim().ToLower())  
  56.                         {  
  57.                             case "companyname":  
  58.                                 query = query.OrderByDescending(q => q.CompanyName);  
  59.                                 break;  
  60.                             case "contactname":  
  61.                                 query = query.OrderByDescending(q => q.ContactName);  
  62.                                 break;  
  63.                             case "country":  
  64.                                 query = query.OrderByDescending(q => q.Country);  
  65.                                 break;  
  66.                             case "city":  
  67.                                 query = query.OrderByDescending(q => q.City);  
  68.                                 break;  
  69.                         }  
  70.                     }  
  71.                 }  
  72.                 else  
  73.                 {  
  74.                     query = query.OrderBy(q => q.CustomerID);  
  75.                 }  
  76.   
  77.                 // step 8 Total rows count   
  78.                 total = query.Count();  
  79.                 // step 9 Paging   
  80.                 if (page.HasValue && limit.HasValue)  
  81.                 {  
  82.                     int start = (page.Value - 1) * limit.Value;  
  83.                     records = query.Skip(start).Take(limit.Value).ToList();  
  84.                 }  
  85.                 else  
  86.                 {  
  87.                     records = query.ToList();  
  88.                 }  
  89.             }  
  90.             // step 10 returing json object  
  91.             return this.Json(new { records, total }, JsonRequestBehavior.AllowGet);  
  92.         }  

Understanding Code Snippet in steps.

  1. In the first step, we create Instance of DatabaseContext for accessing Database.
  2. In the second step, we write Linq query for getting customer
  3. In the third step, the company name parameter which we going to receive from the grid when someone is going to search data with company name, after receiving, first, we are going to check is company name not empty after that we are going to apply where clause to Linq query of the company name.
  4. In the fourth step we are going apply a similar check on the contactName parameter and if it is not empty than we are going to apply where clause to Linq query of contactName.
  5. In fifth step we are going to apply the similar check to the country parameter and if it is not empty than we are going apply where clause to Linq query of the country.
  6. In the sixth step, we are going to apply sorting in ascending order for particular columns (company name, contact name, country, city) if someone has a requirement to add some more columns then they can add.
  7. In the seventh step, we are going to apply sorting in descending order for particular columns (company name, contact name, country, city) if someone has a requirement to add some more columns then they can add.
  8. In the eighth step, we are going calculate a total number of rows.
  9. In ninth step, we are going to apply paging logic
  10. In final step, we are going to return Json object which contains (customer records and total count of customers)

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.

ASP.NET

Project structure after adding Index view.

ASP.NET

Adding Script and CSS reference of Gijgo Grid to Index View

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

  1. <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" type="text/css" />  
  2. <link href="https://cdnjs.cloudflare.com/ajax/libs/gijgo/1.7.0/combined/css/gijgo.min.css" rel="stylesheet" type="text/css" />  
  3. <link href="http://code.gijgo.com/1.7.0/css/demo.css" rel="stylesheet" type="text/css" />  
  4. <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>  
  5. <script src="https://cdnjs.cloudflare.com/ajax/libs/gijgo/1.7.0/combined/js/gijgo.min.js" type="text/javascript"></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="gj-margin-top-10">  
  2.     <table id="grid"></table>  
  3. </div>  

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

Creating Gijgo Grid

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

Code Snippet

  1. <script type="text/javascript">   
  2.   
  3.     $(document).ready(function () {  
  4.         grid = $('#grid').grid({  
  5.             primaryKey: 'CustomerID',  
  6.             dataSource: '/Demo/GetCustomers',  
  7.             columns: [  
  8.                 { field: 'CustomerID', hidden: true },  
  9.                 { field: 'CompanyName', sortable: true },  
  10.                 { field: 'ContactName', sortable: true },  
  11.                 { field: 'ContactTitle', sortable: false },  
  12.                 { field: 'Country', sortable: true },  
  13.                 { field: 'City', sortable: true },  
  14.                 { field: 'PostalCode', sortable: false },  
  15.                 { field: 'Phone', sortable: false }  
  16.                   
  17.             ]  
  18.         });  
  19.     });  
  20.   
  21. </script>  

After setting up a script for creating Gijgo 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 just we need to add a small property to the grid. In that, you can see limit property which we can set to display a number of records on the grid.

  1. pager: { limit: 5 }  

Code Snippet

  1. <script type="text/javascript">   
  2.   
  3.     $(document).ready(function () {  
  4.         grid = $('#grid').grid({  
  5.             primaryKey: 'CustomerID',  
  6.             dataSource: '/Demo/GetCustomers',  
  7.             columns: [  
  8.                 { field: 'CustomerID', hidden: true },  
  9.                 { field: 'CompanyName', sortable: true },  
  10.                 { field: 'ContactName', sortable: true },  
  11.                 { field: 'ContactTitle', sortable: false },  
  12.                 { field: 'Country', sortable: true },  
  13.                 { field: 'City', sortable: true },  
  14.                 { field: 'PostalCode', sortable: false },  
  15.                 { field: 'Phone', sortable: false }  
  16.                   
  17.             ],  
  18.             pager: { limit: 5 }  
  19.         });  
  20.     });  
  21.   
  22. </script>  

Snapshot of paging

ASP.NET

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

Debugging view
ASP.NET

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

Adding new Customer

In this part, we are going to create a new customer, and  for doing that we need to create a dialog because when we are going to click on add new customer button a dialog will pop up and in that popup, we are going add details and click on save button to save details.

On the index, view we are going to add a button and a dialog box markup.

Markup for button

  1. <div class="gj-float-right">  
  2.         <button id="btnAdd" type="button" class="gj-button-md">Add New Customer</button>  
  3. </div>  

Markup for dialog

In this part you see that we have created a simple dialog using div tags and inside this tags we have added all textbox controls for taking input and this all controls name are similar to names of customer model, which helps in model binding.

Along with that, you can see two buttons in that; one for saving and the other for cancelling.

  1. <div id="dialog" class="gj-display-none">  
  2.     <div data-role="body">  
  3.         <input type="hidden" id="CustomerID"/>  
  4.         <div class="">  
  5.             <input type="text" class="gj-textbox-md" id="CompanyName" placeholder="CompanyName...">  
  6.             <input type="text" class="gj-textbox-md" id="ContactName" placeholder="ContactName...">  
  7.             <input type="text" class="gj-textbox-md" id="ContactTitle" placeholder="ContactTitle...">  
  8.             <input type="text" class="gj-textbox-md" id="Address" placeholder="Address...">  
  9.             <input type="text" class="gj-textbox-md" id="City" placeholder="City...">  
  10.             <input type="text" class="gj-textbox-md" id="Region" placeholder="Region...">  
  11.             <input type="text" class="gj-textbox-md" id="PostalCode" placeholder="PostalCode...">  
  12.             <input type="text" class="gj-textbox-md" id="Country" placeholder="Country...">  
  13.             <input type="text" class="gj-textbox-md" id="Phone" placeholder="Phone...">  
  14.             <input type="text" class="gj-textbox-md" id="Fax" placeholder="Fax...">  
  15.         </div>  
  16.     </div>  
  17.     <div data-role="footer">  
  18.         <button type="button" id="btnSave" class="gj-button-md">Save</button>  
  19.         <button type="button" id="btnCancel" class="gj-button-md">Cancel</button>  
  20.     </div>  
  21. </div>  

After adding markup, you can see how the dialog will look:

Snapshot of Add Customer Dialog

ASP.NET

Now to display dialog we need to write some jQuery code.

In jQuery code first, we are going write code for Creating dialog.

Code Snippet

  1. dialog = $('#dialog').dialog({  
  2.      autoOpen: false,  
  3.      resizable: false,  
  4.      modal: true,  
  5.      width: 360  
  6.  });  

After writing code for Creating dialog next on click of add button we need to display dialog along with fields in it.

For doing that we have written click event of add button and in that, we have cleared all textboxes on a load of dialog.

The name of dialog is 'Add Customer'

Code Snippet

  1. $('#btnAdd').on('click',  
  2.     function () {  
  3.         $('#CustomerID').val('');  
  4.         $('#CompanyName').val('');  
  5.         $('#ContactName').val('');  
  6.         $('#ContactTitle').val('');  
  7.         $('#Country').val('');  
  8.         $('#City').val('');  
  9.         $('#PostalCode').val('');  
  10.         $('#Phone').val('');  
  11.   
  12.         dialog.open('Add Customer');  
  13.   
  14.     });  

Complete Code Snippet after adding Dialog

  1. <script type="text/javascript">  
  2. var grid, dialog;  
  3.         $(document).ready(function ()   
  4.         {  
  5.             grid = $('#grid').grid({  
  6.                 primaryKey: 'CustomerID',  
  7.                 dataSource: '/Demo/GetCustomers',  
  8.                 columns: [  
  9.                     { field: 'CustomerID', hidden: true },  
  10.                     { field: 'CompanyName', sortable: true },  
  11.                     { field: 'ContactName', sortable: true },  
  12.                     { field: 'ContactTitle', sortable: false },  
  13.                     { field: 'Country', sortable: true },  
  14.                     { field: 'City', sortable: true },  
  15.                     { field: 'PostalCode', sortable: false },  
  16.                     { field: 'Phone', sortable: false }  
  17.                 ],  
  18.                 pager: { limit: 5 }  
  19.             });  
  20.         });  
  21.   
  22.         dialog = $('#dialog').dialog({  
  23.             autoOpen: false,  
  24.             resizable: false,  
  25.             modal: true,  
  26.             width: 360  
  27.         });  
  28.   
  29.         $('#btnAdd').on('click',  
  30.             function () {  
  31.                 $('#CustomerID').val('');  
  32.                 $('#CompanyName').val('');  
  33.                 $('#ContactName').val('');  
  34.                 $('#ContactTitle').val('');  
  35.                 $('#Country').val('');  
  36.                 $('#City').val('');  
  37.                 $('#PostalCode').val('');  
  38.                 $('#Phone').val('');  
  39.                 dialog.open('Add Customer');  
  40.             });  
  41.   
  42.     </script>  

Snapshot after adding Dialog

ASP.NET

Now we have added dialog, so next let’s add another action method which will handle this post request.

Adding Save Action Method

In this part, we are going to create save action method which will take Customer Model as input. After doing that we need to check if ModelState is valid or not. If it is valid then we are going to save customer data into the database.

And if ModelState is invalid then we are going send an error message to view to display.

We are going to use  this action method for both Inserting and updating customers. For making it work we have added a check if CustomerID is present for a customer then we are going to update data not going to insert it, and if not present then we are going to insert a new customer.

Code Snippet

  1. [HttpPost]  
  2.      public JsonResult Save(Customers record)  
  3.      {  
  4.          if (ModelState.IsValid)  
  5.          {  
  6.              using (DatabaseContext context = new DatabaseContext())  
  7.              {  
  8.                  if (record.CustomerID > 0)  
  9.                  {  
  10.                      context.Entry(record).State = EntityState.Modified;  
  11.                      context.SaveChanges();  
  12.                  }  
  13.                  else  
  14.                  {  
  15.                      context.Customers.Add(record);  
  16.                  }  
  17.                  context.SaveChanges();  
  18.              }  
  19.              return Json(new {result = true});  
  20.          }  
  21.          else  
  22.          {  
  23.              var errorList = (from item in ModelState  
  24.                  where item.Value.Errors.Any()  
  25.                  select item.Value.Errors[0].ErrorMessage).ToList();  
  26.   
  27.              return Json(new { result = false, errorList = errorList });  
  28.   
  29.          }  
  30.      }  

Now after adding Save Action Method next, we are going to add Ajax function which will post data from form to action method.

Creating Save Ajax function

In this part we are going to get data from all textboxes and create a record object and then that object we are going send to Save Action Method, for calling Save action method we need to set URL for ajax function which will be “/Demo/Save” (controller/action method) and set method type to “POST”, if data is valid then grid will just reload else it will show error message.

Code Snippet

  1. function Save() {  
  2.       var record =  
  3.       {  
  4.           CustomerID: $('#CustomerID').val(),  
  5.           CompanyName: $('#CompanyName').val(),  
  6.           ContactName: $('#ContactName').val(),  
  7.           ContactTitle: $('#ContactTitle').val(),  
  8.           Country: $('#Country').val(),  
  9.           City: $('#City').val(),  
  10.           PostalCode: $('#PostalCode').val(),  
  11.           Phone: $('#Phone').val()  
  12.       };  
  13.   
  14.       $.ajax({ url: '/Demo/Save', data: { record: record }, method: 'POST' })  
  15.           .done(function (data)  
  16.           {  
  17.               if (data.result == false)  
  18.               {  
  19.                   var message = "";  
  20.                   for (var i = 0; i < data.errorList.length; i++)  
  21.                   {  
  22.                       message += data.errorList[i] + "\n";  
  23.                   }  
  24.   
  25.                   alert(message);  
  26.               }  
  27.               else  
  28.               {  
  29.                   dialog.close();  
  30.                   grid.reload();  
  31.               }  
  32.           })  
  33.           .fail(function() {  
  34.               alert('Failed to save.');  
  35.               dialog.close();  
  36.           });  
  37.   }  
  38. '#btnSave').on('click', Save);  

Now save application and run it once again to see how we can create a new customer.

ASP.NET

Debugging View

ASP.NET

View After adding Customer
ASP.NET

After adding view next, we are going to Edit record.

Editing Customer record

For editing record first, we need to add edit button in grid.

It is simple to add a button; we just need to add simple markup in Grid which is shown below.

Code Snippet for adding Edit button

  1. {width: 64,   
  2. tmpl: '<span class="material-icons gj-cursor-pointer">edit</span>',   
  3. align: 'center',   
  4. events: {'click': Edit}}  

Code Snippet

  1. $(document).ready(function () {  
  2.       grid = $('#grid').grid({  
  3.           primaryKey: 'CustomerID',  
  4.           dataSource: '/Demo/GetCustomers',  
  5.           columns: [  
  6.               { field: 'CustomerID', hidden: true },  
  7.               { field: 'CompanyName', sortable: true },  
  8.               { field: 'ContactName', sortable: true },  
  9.               { field: 'ContactTitle', sortable: false },  
  10.               { field: 'Country', sortable: true },  
  11.               { field: 'City', sortable: true },  
  12.               { field: 'PostalCode', sortable: false },  
  13.               { field: 'Phone', sortable: false },  
  14.               { width: 64, tmpl: '<span class="material-icons gj-cursor-pointer">edit</span>', align: 'center', events: { 'click': Edit } }  
  15.                 
  16.           ],  
  17.           pager: { limit: 5 }  
  18.       });  
  19.   
  20.       $('#btnSave').on('click', Save);  
  21.   });  

After adding edit button it won’t work unless we add Edit Event.

In this Edit event, we are going to show edit dialog with textboxes and row data bound in it which we have chosen to edit.

Code Snippet

  1. function Edit(e)   
  2. {  
  3.         $('#CustomerID').val(e.data.record.CustomerID);  
  4.         $('#CompanyName').val(e.data.record.CompanyName);  
  5.         $('#ContactName').val(e.data.record.ContactName);  
  6.         $('#ContactTitle').val(e.data.record.ContactTitle);  
  7.         $('#Country').val(e.data.record.Country);  
  8.         $('#City').val(e.data.record.City);  
  9.         $('#PostalCode').val(e.data.record.PostalCode);  
  10.         $('#Address').val(e.data.record.Address);  
  11.         $('#Phone').val(e.data.record.Phone);  
  12.         $('#Fax').val(e.data.record.Fax);  
  13.         $('#Region').val(e.data.record.Region);  
  14.         dialog.open('Edit Customer');  
  15.  }  

Now save application and run it once again to see Edit button and Edit Dialog.

Snapshot while displaying Edit dialog

ASP.NET

Wait, wait we missed something --  our Dialog does not get canceled on click of Cancel button.

For closing dialog on cancel we just need to write a small function which is shown below.

Code Snippet

  1. $('#btnCancel').on('click',  
  2.  function ()  
  3.  {  
  4.      dialog.close();  
  5.  });  

Wow, it's working fine, now to update data we do not need to write code because we are going to call same action method which we have created for saving data.

In Save action method we have added a check to see if CustomerID is greater than zero if it is then we are going to update data.

Code Snippet

  1. public JsonResult Save(Customers record)  
  2.         {  
  3.             if (ModelState.IsValid)  
  4.             {  
  5.                 using (DatabaseContext context = new DatabaseContext())  
  6.                 {  
  7.                     if (record.CustomerID > 0)  
  8.                     {  
  9.                         context.Entry(record).State = EntityState.Modified;  
  10.                         context.SaveChanges();  
  11.                     }  
  12.                     else  
  13.                     {  
  14.                         context.Customers.Add(record);  
  15.                     }  
  16.                     context.SaveChanges();  
  17.                 }  
  18.                 return Json(new { result = true });  
  19.             }  
  20.             else  
  21.             {  
  22.                 var errorList = (from item in ModelState  
  23.                                  where item.Value.Errors.Any()  
  24.                                  select item.Value.Errors[0].ErrorMessage).ToList();  
  25.   
  26.                 return Json(new { result = false, errorList = errorList });  
  27.             }  
  28.         }  

Now save the application and run it once again.

Snapshot while Editing Customer details

ASP.NET

Debugging View

ASP.NET

View After Editing /Updating Customer

ASP.NET

After updating data next thing to do is Delete Customer.

Deleting Customer

For deleting customer, the first thing to do is to create Action Method which will handle delete request, and along with that, we need to pass CustomerID as a parameter, on the basis of which we are going to delete a customer.

Code Snippet

  1. [HttpPost]  
  2. public JsonResult Delete(int id)  
  3. {  
  4.     using (DatabaseContext context = new DatabaseContext())  
  5.     {  
  6.         Customers entity = context.Customers.First(p => p.CustomerID == id);  
  7.         context.Customers.Remove(entity);  
  8.         context.SaveChanges();  
  9.     }  
  10.     return Json(new { result = true });  
  11. }  

After adding Delete Action Method for Deleting record next we need to add a Delete button in grid.

It is simple to add a button we just need to add simple markup in Grid which is shown below.

Code Snippet for adding Edit button

  1. {   
  2.    width: 64,   
  3.    tmpl: '<span class="material-icons gj-cursor-pointer">delete</span>',   
  4.    align: 'center',   
  5. events: {'click': Delete}   
  6. }  

Code Snippet

  1. var grid, dialog;  
  2.     $(document).ready(function () {  
  3.         grid = $('#grid').grid({  
  4.             primaryKey: 'CustomerID',  
  5.             dataSource: '/Demo/GetCustomers',  
  6.             columns: [  
  7.                 { field: 'CustomerID', hidden: true },  
  8.                 { field: 'CompanyName', sortable: true },  
  9.                 { field: 'ContactName', sortable: true },  
  10.                 { field: 'ContactTitle', sortable: false },  
  11.                 { field: 'Country', sortable: true },  
  12.                 { field: 'City', sortable: true },  
  13.                 { field: 'PostalCode', sortable: false },  
  14.                 { field: 'Phone', sortable: false },  
  15.                 { width: 64, tmpl: '<span class="material-icons gj-cursor-pointer">edit</span>', align: 'center', events: { 'click': Edit } },  
  16.                 { width: 64, tmpl: '<span class="material-icons gj-cursor-pointer">delete</span>', align: 'center', events: { 'click': Delete } }  
  17.             ],  
  18.             pager: { limit: 5 }  
  19.         });  
  20.   
  21.         $('#btnSave').on('click', Save);  
  22.     });  

After adding Delete button, it won’t work unless we add Delete Event.

In this Delete event we are going to first ask for confirmation after user accepts; to delete then we are going to call Delete Action Method with ajax post and with that we are going to pass CustomerID.

After we delete record finally we are going to reload grid.

Code Snippet

  1. function Delete(e) {  
  2.         if (confirm('Are you sure you want to delete Customer?'))   
  3.         {  
  4.             $.ajax({url: '/Demo/Delete', data: { id: e.data.id }, method: 'POST' })  
  5.                 .done(function () {  
  6.                     grid.reload();  
  7.                 })  
  8.                 .fail(function () {  
  9.                     alert('Failed to delete.');  
  10.                 });  
  11.         }  
  12.     }  

Confirmation Snapshot while deleting data

ASP.NET

Debugging View of Delete Action Method

ASP.NET

After completing with Delete functionally next we are finally going to work on Search.

Search

For adding search to this grid we need to add new text boxes and buttons to search and clear.

We are going to give three parameters to search (Company Name, Contact Name, Country).

Let’s start with adding markup, in this, you can easily find 3 textboxes and 2 buttons.

Code Snippet

  1. <div class="gj-margin-top-10">  
  2.     <div class="gj-float-left">  
  3.         <form class="display-inline">  
  4.             <input id="txtcompanyName" type="text" placeholder="CompanyName..." class="gj-textbox-md gj-display-inline-block gj-width-200"/>  
  5.             <input id="txtcontactName" type="text" placeholder="ContactName..." class="gj-textbox-md gj-display-inline-block gj-width-200"/>  
  6.             <input id="txtcountry" type="text" placeholder="Country..." class="gj-textbox-md gj-display-inline-block gj-width-200"/>  
  7.             <button id="btnSearch" type="button" class="gj-button-md">Search</button>  
  8.             <button id="btnClear" type="button" class="gj-button-md">Clear</button>  
  9.         </form>  
  10.     </div>  
  11.     <div class="gj-float-right">  
  12.         <button id="btnAdd" type="button" class="gj-button-md">Add New Customer</button>  
  13.     </div>  
  14. </div>  

Snapshot after adding Search to Gird

ASP.NET

After adding textboxes and buttons next we are going to write javascript code for searching and clearing textboxes.

In this part, we do not require to add New Action Method we are going to use same Action Method GetCustomers which we are already using for the binding grid on load and also we take three parameters (Company Name, Contact Name, Country) as input which we require for search in that.

Code Snippet

  1. public JsonResult GetCustomers(  
  2. int? page,   
  3. int? limit,   
  4. string sortBy,   
  5. string direction,   
  6. string companyName,   
  7. string contactName,   
  8. string country)  

Now we are going to write a script for searching and clearing search parameter.

Code Snippet

In this part we are going to pass three parameters as input to action Method when user clicks on search button.

  1. $('#btnSearch').on('click',  
  2.      function() {  
  3.          grid.reload({  
  4.              page: 1,  
  5.              companyName: $('#txtcompanyName').val(),  
  6.              contactName: $('#txtcontactName').val(),  
  7.              country: $('#txtcountry').val()  
  8.          });  
  9.      });  

Next we are going to add code snippet for clearing search textboxes on click on Clear button.

  1. $('#btnClear').on('click',  
  2.     function() {  
  3.     $('#txtcompanyName').val('');  
  4.     $('#txtcontactName').val('');  
  5.     $('#txtcountry').val('');     
  6.     grid.reload({ companyName: '', contactName: '', country: '' });  
  7. });  

Now we have completed adding search, so let’s save the application and run it once again.

Snapshot of Search while searching with Company Name

ASP.NET

Debugging View of Company Name Search

ASP.NET

In the same way we can try a search for contact Name and Country.

Finally, if we click on the Clear button it will clear all textboxes of search.

Snapshot of Clearing Search

ASP.NET

Advantages

In this grid, you can easily add search with textboxes and Dropdown which are not available on other grids.

Disadvantages

There is one functionally missing with this grid -- it does not have validation inbuilt you need to write it all while you are adding a new record or editing/updating record.

For More Details, Refer below link

http://gijgo.com/grid

Fnally we have completed Using Gijgo Grid with ASP.NET MVC in a step by step way. I hope you liked this article.


Similar Articles