jQuery Datatable Single And Multi-Row Selection

This article gives an overview of how to use jQuery datatable in MVC to implement single and multiple row selection in jQuery Ajax. I will use jQuery datatable plugin in this demo application and explain how to apply single and multiple row selection. Here is the code.
 
This is final output of application.
 
jQuery Datatable Single And Multi-Row Selection
 
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.
 
jQuery Datatable Single And Multi-Row Selection
 
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 Single And Multi-Row Selection
 
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 Single And Multi-Row Selection
 
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 Single And Multi-Row Selection
 
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.
 
jQuery Datatable Single And Multi-Row Selection
 
Step 5
 
In Visual Studio tools go to NuGet Package Manager and select Manage NuGet Packages for solution.
 
jQuery Datatable Single And Multi-Row Selection
 
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.
  1. using System;  
  2. using System.ComponentModel.DataAnnotations;  
  3.   
  4. namespace JQueryDatatableMultipleRowSelectionMvc_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 Data Folder and add class ApplicationDbContext for database communication.
  1. using JQueryDatatableMultipleRowSelectionMvc_Demo.Models;  
  2. using System.Data.Entity;  
  3.   
  4. namespace JQueryDatatableMultipleRowSelectionMvc_Demo.Data  
  5. {  
  6.     public class ApplicationDbContext : DbContext  
  7.     {  
  8.         public ApplicationDbContext() : base("MultiSelectRowDB")  
  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 bootstrap, jQuery and datatable plugin 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.     <link href="~/Content/DataTables/css/select.bootstrap4.css" rel="stylesheet" />  
  11. </head>  
  12. <body>  
  13.     <div class="container py-4">  
  14.         @RenderBody()  
  15.     </div>  
  16.     @Scripts.Render("~/bundles/jquery")  
  17.     @Scripts.Render("~/bundles/bootstrap")  
  18.     <script src="~/Scripts/jquery-3.5.1.min.js"></script>  
  19.     <script src="~/Scripts/DataTables/jquery.dataTables.min.js"></script>  
  20.     <script src="~/Scripts/DataTables/dataTables.bootstrap4.min.js"></script>  
  21.     <script src="~/Scripts/DataTables/dataTables.select.min.js"></script>  
  22.     @RenderSection("scripts", required: false)  
  23. </body>  
  24. </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.
  1. using JQueryDatatableMultipleRowSelectionMvc_Demo.Data;  
  2. using System.Linq;  
  3. using System.Web.Mvc;  
  4.   
  5. namespace JQueryDatatableCopyExcelPdfCSVPrintButtonMvc_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. <button id="button" class="btn btn-primary rounded-0 mb-2">Row Count</button>  
  7. <table id="example" class="table table-bordered" style="width:100%;">  
  8.     <thead class="bg-primary text-white">  
  9.         <tr>  
  10.             <th>Id</th>  
  11.             <th>Name</th>  
  12.             <th>Position</th>  
  13.             <th>Office</th>  
  14.             <th>Age</th>  
  15.             <th>Start Date</th>  
  16.             <th>Salary</th>  
  17.         </tr>  
  18.     </thead>  
  19. </table>  
  20.   
  21. @section scripts{  
  22.     <script type="text/javascript">  
  23.         $(document).ready(function () {  
  24.             var table = $('#example').DataTable({  
  25.                 //for single row selection use this  
  26.                 //select: {  
  27.                 //    style: 'single'  
  28.                 //},  
  29.                 "ajax": {  
  30.                     "url"'/Home/GetData',  
  31.                     "type"'GET',  
  32.                     "dataType"'json',  
  33.                 },  
  34.                 "columns": [  
  35.                     { 'data''Id' },  
  36.                     { 'data''Name' },  
  37.                     { 'data''Position' },  
  38.                     { 'data''Office' },  
  39.                     { 'data''Age' },  
  40.                     {  
  41.                         'data''StartDate',  
  42.                         'render': function (jsonDate) {  
  43.                             var date = new Date(parseInt(jsonDate.substr(6)));  
  44.                             var month = ("0" + (date.getMonth() + 1)).slice(-2);  
  45.                             return ("0" + date.getDate()).slice(-2) + '-' + month + '-' + date.getFullYear();  
  46.                         }  
  47.                     },  
  48.                     {  
  49.                         'data''Salary',  
  50.                         'render': function (salary) {  
  51.                             return '$' + salary;  
  52.                         }  
  53.                     }  
  54.                 ],  
  55.             });  
  56.             $('#example tbody').on('click''tr', function () {  
  57.                 $(this).toggleClass('selected');  
  58.             });  
  59.             $('#button').click(function () {  
  60.                 alert(table.rows('.selected').data().length + ' row(s) selected');  
  61.             });  
  62.         });  
  63.     </script>  
  64. }   
Step 12
 
Now it’s time to build and run your application >> ctrl+F5
 
jQuery Datatable Single And Multi-Row Selection


Similar Articles