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:
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.
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.
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.
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).
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.
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
Step 6
Right-click on Models Folder and choose a new item, “Add” class Employee.
- using System;
- using System.ComponentModel.DataAnnotations;
-
- namespace JQueryDatatableHideShowColumnsMvc_Demo.Models
- {
- public class Employee
- {
- [Key]
- public int Id { get; set; }
-
- [Required]
- [StringLength(100)]
- public string Name { get; set; }
-
- [Required]
- [StringLength(100)]
- public string Position { get; set; }
-
- [Required]
- [StringLength(100)]
- public string Office { get; set; }
-
- [Required]
- public int Age { get; set; }
-
- [Required]
- [DataType(DataType.Date)]
- public DateTime StartDate { get; set; }
-
- [Required]
- [DataType(DataType.Currency)]
- public decimal Salary { get; set; }
- }
- }
Step 7
Create a Data Folder and add the class ApplicationDbContext for database communication.
- using JQueryDatatableHideShowColumnsMvc_Demo.Models;
- using System.Data.Entity;
-
- namespace JQueryDatatableHideShowColumnsMvc_Demo.Data
- {
- public class ApplicationDbContext : DbContext
- {
- public ApplicationDbContext() : base("EmployeeDB")
- {
-
- }
-
- public DbSet<Employee> Employees { get; set; }
- }
- }
Step 8
- Enable-migrations
- Add-Migration InitialModel
- Update-database
Step 9
Add the bootstrap, jQuery and datatable plugins in _Layout.cshtm
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>@ViewBag.Title</title>
- @Styles.Render("~/Content/css")
- @Scripts.Render("~/bundles/modernizr")
- <link href="~/Content/DataTables/css/dataTables.bootstrap4.min.css" rel="stylesheet" />
- </head>
- <body>
- <div class="container py-4">
- @RenderBody()
- </div>
- @Scripts.Render("~/bundles/jquery")
- @Scripts.Render("~/bundles/bootstrap")
- <script src="~/Scripts/DataTables/jquery.dataTables.min.js"></script>
- <script src="~/Scripts/DataTables/dataTables.bootstrap4.min.js"></script>
- @RenderSection("scripts", required: false)
- </body>
- </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.
- using JQueryDatatableHideShowColumnsMvc_Demo.Data;
- using System.Linq;
- using System.Web.Mvc;
-
- namespace JQueryDatatableHideShowColumnsMvc_Demo.Controllers
- {
- public class HomeController : Controller
- {
- private readonly ApplicationDbContext db = new ApplicationDbContext();
- public ActionResult Index()
- {
- return View();
- }
-
- public ActionResult GetData()
- {
- var employee = db.Employees.ToList();
- return Json(new { data = employee }, JsonRequestBehavior.AllowGet);
- }
- }
- }
Step 11
In views folder Under Home folder in Index.cshtml view. Add the following code:
- @{
- ViewBag.Title = "Home";
- }
-
- <h3 class="text-center text-uppercase">List of employees</h3>
-
- <div class="mb-2">
- <b>Show/Hide Column : </b>
- <a class="showHideColumn" data-columnindex="0">Id</a> -
- <a class="showHideColumn" data-columnindex="1">Name</a> -
- <a class="showHideColumn" data-columnindex="2">Position</a> -
- <a class="showHideColumn" data-columnindex="3">Office</a> -
- <a class="showHideColumn" data-columnindex="4">Age</a> -
- <a class="showHideColumn" data-columnindex="5">Start Date</a> -
- <a class="showHideColumn" data-columnindex="6">Salary</a> -
- </div>
-
- <table id="example" class="table table-bordered" style="width:100%;">
- <thead>
- <tr>
- <th>Id</th>
- <th>Name</th>
- <th>Position</th>
- <th>Office</th>
- <th>Age</th>
- <th>Start Date</th>
- <th>Salary</th>
- </tr>
- </thead>
- </table>
-
- @section scripts{
- <script type="text/javascript">
- $(document).ready(function () {
- var datatableInstance = $('#example').DataTable({
- "ajax": {
- "url": '/Home/GetData',
- "type": 'GET',
- "dataType": 'json',
- },
- "columns": [
- { 'data': 'Id' },
- { 'data': 'Name' },
- { 'data': 'Position' },
- { 'data': 'Office' },
- { 'data': 'Age' },
- {
- 'data': 'StartDate',
- 'render': function (jsonDate) {
- var date = new Date(parseInt(jsonDate.substr(6)));
- var month = ("0" + (date.getMonth() + 1)).slice(-2);
- return ("0" + date.getDate()).slice(-2) + '-' + month + '-' + date.getFullYear();
- }
- },
- {
- 'data': 'Salary',
- 'render': function (salary) {
- return '$' + salary;
- }
- }
- ]
- });
-
- $('.showHideColumn').on('click', function (e) {
- e.preventDefault();
-
- var tableColumn =
- datatableInstance.column($(this).attr('data-columnindex'));
- tableColumn.visible(!tableColumn.visible());
- });
- });
- </script>
- }
Step 12
Now it’s time to build and run your application >> ctrl+F5