ASP.NET MVC - jQuery Ajax Datatables with Dynamic Columns

Introduction 

 
Jquery Datatables free plugin offers many useful features to integrate and customize a table with many web development platforms. Today, I shall be demonstrating the dynamic number of columns loading using server-side Ajax Jquery Datatables plugin with ASP.NET MVC5 platform.
 
 

Prerequisites
 
The following are some prerequisites before you proceed any further in this tutorial:
  1. Installation of Jquery Datatebles plugin.
  2. Understanding Jquery Datatebles plugin Integration with ASP.NET MVC5
  3. Installation of CSVLibraryAK.
  4. Knowledge of ASP.NET MVC5.
  5. Knowledge of HTML.
  6. Knowledge of JavaScript.
  7. Knowledge of Bootstrap.
  8. Knowledge of Jquery.
  9. Knowledge of C# Programming.
The example code is being developed in Microsoft Visual Studio 2017 Professional. I have taken the data sample from AdventureWorks for SQL Server 2014 and Iris data-set from UCI Machine Learning Repository.
 
Let's begin now.
 
Step 1
 
Create a new MVC web project and name it "MVCAjaxDatatablesDynamicCol".  
 
Step 2
 
Now, create a controller file and name it "Controllers\HomeController.cs" and write a simple POST Index(...) method which will uploaded the provided CSV file to the server so that Jquery Datatables server-side can process the uploaded file and load th data.
 
Know that jquery data tables support the following JSON format, i.e.:
  1. [{  
  2.  "columns": [{  
  3.   "title""col1_name",  
  4.   "data""col1_name"  
  5.  }, {  
  6.   "title""col2_name",  
  7.   "data""col2_name"  
  8.  }],  
  9.  "data": [{  
  10.   "col1_name""col1 data",  
  11.   "col2_name""col2 data"  
  12.  }, {  
  13.   "col1_name""col1 data",  
  14.   "col2_name""col2 data"  
  15.  }]  
  16. }] 
Step 3
 
In "Controllers\HomeController.cs" file for server-side, Jquery Datatables is needed to work for a dynamic number of columns. We need to write necessary Ajax method i.e.
  1. ...  
  2.         public ActionResult GetData()  
  3.         {  
  4.             // Initialization.  
  5.             JsonResult result = new JsonResult();  
  6.   
  7.             try  
  8.             {  
  9.                 // Initialization Jquery Datatables.  
  10.                 string search = Request.Form.GetValues("search[value]")[0];  
  11.                 string draw = Request.Form.GetValues("draw")[0];  
  12.                 string order = Request.Form.GetValues("order[0][column]")[0];  
  13.                 string orderDir = Request.Form.GetValues("order[0][dir]")[0];  
  14.                 int startRec = Convert.ToInt32(Request.Form.GetValues("start")[0]);  
  15.                 int pageSize = Convert.ToInt32(Request.Form.GetValues("length")[0]);  
  16. ...  
  17.                 // Initialization.  
  18.                 JqDataObj dataObj = new JqDataObj();  
  19. ...  
  20.                 // Load uploaded file Data.  
  21. ...  
  22.                 // Set Jquery Datatable Total record count.  
  23.                 int totalRecords = data.Rows.Count;  
  24.   
  25.                 // Apply Jquery Datatables Search.  
  26. ...  
  27.                 // Apply Jquery Datatable Sorting.  
  28. ...  
  29.                 // Set Jquery Datatable Filter record count.  
  30.                 int recFilter = data.Rows.Count;  
  31.   
  32.                 // Apply Jquery Datatable Pagination.  
  33. ...  
  34.                 // Set Jquery Datatable Dynamic Header Column Names.  
  35.                 dataObj.columns = this.LoadColumnHeader(data);  
  36. ...  
  37.                 // Set Jquery Datatable Data Rows.  
  38.                 dataObj.data = data;  
  39. ...  
  40.                 // Set Jquery Datatable resultant information.  
  41.                 result = this.Json(new { draw = Convert.ToInt32(draw), recordsTotal = totalRecords, recordsFiltered = recFilter, data = JsonConvert.SerializeObject(dataObj) }, JsonRequestBehavior.AllowGet);  
  42.             }  
  43.             catch (Exception ex)  
  44.             {  
  45.                 // Info  
  46.                 Console.Write(ex);  
  47.             }  
  48.   
  49.             // Return info.  
  50.             return result;  
  51.         }  
  52. ... 
The above "GetData(...)" Ajax method will be called by the Jquery Datatables to load the required data into the table form.
 
Step 4
 
Now, create your view and name it "Views\Home\Index.cshtml". The view should contain a CSV file uploading component along with a table place holder for Jquery Datatables plugin to integrate with, i.e.:
  1. ...  
  2.     <!-- HTML Code to upload CSV file -->  
  3. ...  
  4.     <!-- HTML Code for JQuery Datatables Plugin to integrate with -->  
  5.     <div class="row">  
  6.         <div>  
  7.            <table class="table table-striped table-bordered table-hover"  
  8.                id="TableId"  
  9.                cellspacing="0"  
  10.                align="center"  
  11.                width="100%">  
  12.   
  13.            </table>  
  14.         </div>  
  15.     </div>  
  16. ... 
In the above code, I have simply created a table that will integrate the jquery datatables plugin with the User Interface (UI), I am skipping the HTML code to upload the CSV file.
 
Step 5
 
Finally, create the JavaScript file "Scripts\script-custom-datatable.js" which will load our dynamic number of columns into the server-side jquery datatables plugin, i.e.:
  1. ...  
  2.     $(document).ready(function ()  
  3.     {  
  4. ...                    $('#TableId').DataTable(  
  5.                         {  
  6.                             "columnDefs": [  
  7.                                 { "searchable"true"orderable"true, targets: "_all" },  
  8.                                 { "className""text-center custom-middle-align", targets: "_all" }  
  9.                             ],  
  10. ...                              
  11.                             "processing"true,  
  12.                             "serverSide"true,  
  13.                             "ajax":  
  14.                             {  
  15.                                 "url""/Home/GetData",  
  16.                                 "type""POST",  
  17.                                 "dataType""JSON",  
  18.                                 "dataSrc"function (json)  
  19.                                 {  
  20.                                     // Settings.  
  21.                                     jsonObj = $.parseJSON(json.data)  
  22.   
  23.                                     // Data  
  24.                                     return jsonObj.data;  
  25.                                 }  
  26.                             },  
  27.                             "columns": dataObject.columns  
  28.                         });  
  29. ...  
  30.     });  
  31. ... 
In the above code, I have configured the Jquery Datatables plugin with server-side Ajax call in order to load the dynamic columns data as uploaded by the user.
 
Step 6
 
Now, execute the project and you will be able to see the following in action, i.e.:
 


 

 

Conclusion

 
In this article, you learned to configure server-side jquery datatables plugin to support dynamic number of columns loading in ASP.NET MVC web platform. You also learned how to configure the Ajax method that supports the Jquery Datatables plugin in ASP.NET MVC.


Similar Articles