jQuery Datatable - Hide & Show Columns

Introduction 

 
This article gives an overview of how to use jQuery datatable in MVC Hide and Show columns, in jQuery Ajax. I will use jQuery datatable plugin in this demo application and explain how to apply the hide and show function. Here is the code.
 
This example requires the following basic understandings:
  • JQuery datatable
  • Ajax
  • Bootstrap
  • Entity framework
  • MVC
Here is the output for this application:
 
jQuery Datatable Hide Show Columns
 
Step 1
 
There are multiple ways to create a new project in Visual Studio 2019. When you first open Visual Studio, the start window appears. From there, you can choose to create a new project.
 
jQuery Datatable Hide Show Columns
 
If the Visual Studio development environment is already open, you can create a new project by choosing File > New > Project on the menu bar or by clicking the New Project button on the toolbar.
 
jQuery Datatable Hide Show Columns
 
Step 2
 
On the Create a new project page, a list of your recently selected templates appears on the left. The templates are sorted by most recently used. 
 
If you're not selecting from the recently used templates, you can filter all available project templates by Language (for example, C#), Platform (for example, Windows or Azure), and Project type (for example, Desktop or Web). You can also enter search text into the search box to further filter the templates, for example, ASP.NET.
 
jQuery Datatable Hide Show Columns
 
Select a template and then click Next.
 
Step 3
 
The Configure your new project page has options to name your project (and solution), choose a disk location, and select a Framework version (if applicable to the template you chose).
 
jQuery Datatable Hide Show Columns
 
Click Create to create a new project.
 
Step 4
 
In create a new ASP.NET Web Application window, choose MVC template and click on create. Visual Studio will generate an MVC Web Application project for you.
 
jQuery Datatable Hide Show Columns
 
Step 5
 
In Visual Studio tools, go to NuGet Package Manager and select Manage NuGet Packages for the solution.
 
Install the following package for this application:
  • Bootstrap latest version
  • Jquery latest version
  • Datatables latest version
  • Entity framework latest version
jQuery Datatable Hide Show Columns
 
Step 6
 
Right-click on Models Folder and choose a new item, “Add” class Employee.
  1. using System;  
  2. using System.ComponentModel.DataAnnotations;  
  3.   
  4. namespace JQueryDatatableHideShowColumnsMvc_Demo.Models  
  5. {  
  6.     public class Employee  
  7.     {  
  8.         [Key]  
  9.         public int Id { getset; }  
  10.   
  11.         [Required]  
  12.         [StringLength(100)]  
  13.         public string Name { getset; }  
  14.   
  15.         [Required]  
  16.         [StringLength(100)]  
  17.         public string Position { getset; }  
  18.   
  19.         [Required]  
  20.         [StringLength(100)]  
  21.         public string Office { getset; }  
  22.   
  23.         [Required]  
  24.         public int Age { getset; }  
  25.   
  26.         [Required]  
  27.         [DataType(DataType.Date)]  
  28.         public DateTime StartDate { getset; }  
  29.   
  30.         [Required]  
  31.         [DataType(DataType.Currency)]  
  32.         public decimal Salary { getset; }  
  33.     }  
  34. }   
Step 7
 
Create a Data Folder and add the class ApplicationDbContext for database communication.
  1. using JQueryDatatableHideShowColumnsMvc_Demo.Models;  
  2. using System.Data.Entity;  
  3.   
  4. namespace JQueryDatatableHideShowColumnsMvc_Demo.Data  
  5. {  
  6.     public class ApplicationDbContext : DbContext  
  7.     {  
  8.         public ApplicationDbContext() : base("EmployeeDB")  
  9.         {  
  10.   
  11.         }  
  12.   
  13.         public DbSet<Employee> Employees { getset; }  
  14.     }  
  15. }   
Step 8
  1. Enable-migrations
  2. Add-Migration InitialModel
  3. Update-database
Step 9
 
Add the bootstrap, jQuery and datatable plugins in _Layout.cshtm
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <meta charset="utf-8" />  
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">  
  6.     <title>@ViewBag.Title</title>  
  7.     @Styles.Render("~/Content/css")  
  8.     @Scripts.Render("~/bundles/modernizr")  
  9.     <link href="~/Content/DataTables/css/dataTables.bootstrap4.min.css" rel="stylesheet" />  
  10. </head>  
  11. <body>  
  12.     <div class="container py-4">  
  13.         @RenderBody()  
  14.     </div>  
  15.     @Scripts.Render("~/bundles/jquery")  
  16.     @Scripts.Render("~/bundles/bootstrap")  
  17.     <script src="~/Scripts/DataTables/jquery.dataTables.min.js"></script>  
  18.     <script src="~/Scripts/DataTables/dataTables.bootstrap4.min.js"></script>  
  19.     @RenderSection("scripts", required: false)  
  20. </body>  
  21. </html>   
Step 10
 
You already have HomeController in the Controllers folder if you don’t have it. Add HomeController in the Controllers folder and write the following code.
  1. using JQueryDatatableHideShowColumnsMvc_Demo.Data;  
  2. using System.Linq;  
  3. using System.Web.Mvc;  
  4.   
  5. namespace JQueryDatatableHideShowColumnsMvc_Demo.Controllers  
  6. {  
  7.     public class HomeController : Controller  
  8.     {  
  9.         private readonly ApplicationDbContext db = new ApplicationDbContext();  
  10.         public ActionResult Index()  
  11.         {  
  12.             return View();  
  13.         }  
  14.   
  15.         public ActionResult GetData()  
  16.         {  
  17.             var employee = db.Employees.ToList();  
  18.             return Json(new { data = employee }, JsonRequestBehavior.AllowGet);  
  19.         }  
  20.     }  
  21. }   
Step 11
 
In views folder Under Home folder in Index.cshtml view. Add the following code:
  1. @{  
  2.     ViewBag.Title = "Home";  
  3. }  
  4.   
  5. <h3 class="text-center text-uppercase">List of employees</h3>  
  6.   
  7. <div class="mb-2">  
  8.     <b>Show/Hide Column : </b>  
  9.     <a class="showHideColumn" data-columnindex="0">Id</a> -  
  10.     <a class="showHideColumn" data-columnindex="1">Name</a> -  
  11.     <a class="showHideColumn" data-columnindex="2">Position</a> -  
  12.     <a class="showHideColumn" data-columnindex="3">Office</a> -  
  13.     <a class="showHideColumn" data-columnindex="4">Age</a> -  
  14.     <a class="showHideColumn" data-columnindex="5">Start Date</a> -  
  15.     <a class="showHideColumn" data-columnindex="6">Salary</a> -  
  16. </div>  
  17.   
  18. <table id="example" class="table table-bordered" style="width:100%;">  
  19.     <thead>  
  20.         <tr>  
  21.             <th>Id</th>  
  22.             <th>Name</th>  
  23.             <th>Position</th>  
  24.             <th>Office</th>  
  25.             <th>Age</th>  
  26.             <th>Start Date</th>  
  27.             <th>Salary</th>  
  28.         </tr>  
  29.     </thead>  
  30. </table>  
  31.   
  32. @section scripts{  
  33.     <script type="text/javascript">  
  34.         $(document).ready(function () {  
  35.             var datatableInstance = $('#example').DataTable({  
  36.                 "ajax": {  
  37.                     "url"'/Home/GetData',  
  38.                     "type"'GET',  
  39.                     "dataType"'json',  
  40.                 },  
  41.                 "columns": [  
  42.                     { 'data''Id' },  
  43.                     { 'data''Name' },  
  44.                     { 'data''Position' },  
  45.                     { 'data''Office' },  
  46.                     { 'data''Age' },  
  47.                     {  
  48.                         'data''StartDate',  
  49.                         'render': function (jsonDate) {  
  50.                             var date = new Date(parseInt(jsonDate.substr(6)));  
  51.                             var month = ("0" + (date.getMonth() + 1)).slice(-2);  
  52.                             return ("0" + date.getDate()).slice(-2) + '-' + month + '-' + date.getFullYear();  
  53.                         }  
  54.                     },  
  55.                     {  
  56.                         'data''Salary',  
  57.                         'render': function (salary) {  
  58.                             return '$' + salary;  
  59.                         }  
  60.                     }  
  61.                 ]  
  62.             });  
  63.   
  64.             $('.showHideColumn').on('click', function (e) {  
  65.                 e.preventDefault();  
  66.   
  67.                 var tableColumn =  
  68.                     datatableInstance.column($(this).attr('data-columnindex'));  
  69.                 tableColumn.visible(!tableColumn.visible());  
  70.             });  
  71.         });  
  72.     </script>  
  73. }   
Step 12
 
Now it’s time to build and run your application >> ctrl+F5
 
jQuery Datatable Hide Show Columns