This article gives an overview of how to use jQuery datatable in MVC to implement copy, Excel, Pdf, CSV and Print button in jQuery Ajax. I will use the jQuery datatable plugin in this demo application. Here is the
code.
This is the final output of application.
This example requires the following basic understanding
- JQuery datatable
- Ajax
- Bootstrap
- Entity framework
- MVC
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, and 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 the new project.
Step 4
In create a new ASP.NET Web Application window choose MVC template click on create. Visual studio will generate MVC Web Application project for you.
Step 5
In Visual Studio tools go to NuGet Package Manager and select Manage NuGet Packages for 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 choose new item “Add” class Employee.
- using System;
- using System.ComponentModel.DataAnnotations;
-
- namespace JQueryDatatableCopyExcelPdfCSVPrintButtonMvc_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 Data Folder and add class ApplicationDbContext for database communication.
- using JQueryDatatableCopyExcelPdfCSVPrintButtonMvc_Demo.Models;
- using System.Data.Entity;
-
- namespace JQueryDatatableCopyExcelPdfCSVPrintButtonMvc_Demo.Data
- {
- public class ApplicationDbContext : DbContext
- {
- public ApplicationDbContext() : base("EmployeeDB")
- {
-
- }
-
- public DbSet<Employee> Employees { get; set; }
- }
- }
- © 2020 GitHub, Inc.
Step 8
- Enable-migrations
- Add-Migration InitialModel
- Update-database
Step 9
Add bootstrap, jQuery and datatable plugin 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/fontawesome-all.min.css" rel="stylesheet" />
- <link href="~/Content/DataTables/css/dataTables.bootstrap4.min.css" rel="stylesheet" />
- <link href="~/Content/DataTables/css/buttons.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/jquery-3.5.1.min.js"></script>
- <script src="~/Scripts/DataTables/jquery.dataTables.min.js"></script>
- <script src="~/Scripts/DataTables/dataTables.bootstrap4.min.js"></script>
- <script src="https://cdn.datatables.net/buttons/1.6.2/js/dataTables.buttons.min.js"></script>
- <script src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.bootstrap4.min.js"></script>
- <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
- <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
- <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
- <script src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.html5.min.js"></script>
- <script src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.print.min.js"></script>
- <script src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.colVis.min.js"></script>
- @RenderSection("scripts", required: false)
- </body>
- </html>
Step 10
You already have HomeController in Controllers folder. If you don’t have it add HomeController in Controllers folder and write the following code.
- using JQueryDatatableCopyExcelPdfCSVPrintButtonMvc_Demo.Data;
- using System.Linq;
- using System.Web.Mvc;
-
- namespace JQueryDatatableCopyExcelPdfCSVPrintButtonMvc_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>
-
- <table id="example" class="table table-bordered" style="width:100%;">
- <thead class="thead-dark">
- <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 () {
- $('#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;
- }
- }
- ],
- "dom": 'Bfrtip',
- "buttons": [
- {
- extend: 'copy',
- className: 'btn btn-dark rounded-0',
- text: '<i class="far fa-copy"></i> Copy'
- },
- {
- extend: 'excel',
- className: 'btn btn-dark rounded-0',
- text: '<i class="far fa-file-excel"></i> Excel'
- },
- {
- extend: 'pdf',
- className: 'btn btn-dark rounded-0',
- text: '<i class="far fa-file-pdf"></i> Pdf'
- },
- {
- extend: 'csv',
- className: 'btn btn-dark rounded-0',
- text: '<i class="fas fa-file-csv"></i> CSV'
- },
- {
- extend: 'print',
- className: 'btn btn-dark rounded-0',
- text: '<i class="fas fa-print"></i> Print'
- }
- ]
- });
- });
- </script>
- }
Step 12
Now it’s time to build and run your application >> ctrl+F5