Bind multiple jquery datatable in one ajax hit in asp.net mvc

As we all know Jquery DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, based upon the foundations of progressive enhancement, and will add advanced interaction controls to any HTML table.

Its very easy to use and manage, we can manage datatable in one ajax hit, but if wants to bind multiple datatables in one ajax hit then here the solution. This article is bit large but hope you spend time to understand and implementation.

you should have datatable js files in the header like below, I am using jquery datatable with twitter bootstrap in below example

<head>
<script src="//cdn.datatables.net/1.10.2/js/jquery.dataTables.min.js"></script>
<script src="//cdn.datatables.net/plug-ins/725b2a2115b/integration/bootstrap/3/dataTables.bootstrap.js"></script>
</head>

Below I am going to bind multiple datatables in one ajax hit
you should have to define thee datatales in html with whom you will bind output like below,

In the below example I am using same datatables for each ajax hit and same server side function to bind each datatables to reduce code, but you can change the structure of each datatables as per server side values returned. I am returing three values from the server side so i given three table headings in html code and three aoColumns columns in script code


// First Datatable design with id DataTable
 <div class="table-responsive" style="padding: 10px;">
 <table id="DataTable" class="table table-striped table-bordered table-hover 
 dataTable margin-top10" aria-describedby="DataTable_info">
 <thead style="cursor: pointer">
 <tr role="row">
 <th>JobId #</th>
 <th class="hidden-sm sorting">Cost Code</th>
 <th class="sorting">Invoice</th>
 <th class="sorting">Amount ($)</th>
 </tr>
 </thead>
 <tbody role="alert" aria-live="polite" aria-relevant="all">
 </tbody>
 </table>
 </div>


// Second Datatable design with id DataTable, 
//you can change id in html and script code as well next time.

 <div class="table-responsive" style="padding: 10px;">
 <table id="DataTable" class="table table-striped table-bordered table-hover 
 dataTable margin-top10" aria-describedby="DataTable_info">
 <thead style="cursor: pointer">
 <tr role="row">
 <th>JobId #</th>
 <th class="hidden-sm sorting">Cost Code</th>
 <th class="sorting">Invoice</th>
 <th class="sorting">Amount ($)</th>
 </tr>
 </thead>
 <tbody role="alert" aria-live="polite" aria-relevant="all">
 </tbody>
 </table>
 </div>



// Third Datatable design with id DataTable, 
//you can change id in html and script code as well next time.
 <div class="table-responsive" style="padding: 10px;">
 <table id="DataTable" class="table table-striped table-bordered table-hover 
 dataTable margin-top10" aria-describedby="DataTable_info">
 <thead style="cursor: pointer">
 <tr role="row">
 <th>JobId #</th>
 <th class="hidden-sm sorting">Cost Code</th>
 <th class="sorting">Invoice</th>
 <th class="sorting">Amount ($)</th>
 </tr>
 </thead>
 <tbody role="alert" aria-live="polite" aria-relevant="all">
 </tbody>
 </table>
 </div>

On button click ajax event will fire and bind above three datatables one by one. you should have server side function which will return output. You have to specify the server side function url in sAjaxSource

 $('#button').click(function (e) {
            //debugger;
            $('.tab-v1').removeClass('hidden');
            var aData = t.rows($(this).closest('tr')).data();
            var job = aData[0][0];
            (function ($) {
                //Code for Revenu Posted Details Datatable
                $.ajax({
                    oTable: $('#DataTable').dataTable({
                        "bAutoWidth": false,
                        cache: false,
                        "bServerSide": true,
                        "bDestroy": true,
                        "sAjaxSource": '@Url.Action("Action1", "Controller")',
                        "bProcessing": true,
                        "bJqueryUI": true,
                        "sPaginationType": "full_numbers",
                        "iDisplayLength": 5,
                        "aLengthMenu": [[5, 7, 10, 25, 50, -1], [5, 7, 10, 25, 50, "All"]],
                        "aaSorting": [[1, "desc"]],
                        "fnServerParams": function (aoData) {
                            aoData.push({ "name": "Job", "value": job });
                        },
                        "fnDrawCallback": function () {
                        },

                        "aoColumns": [
                            {
                                "sName": "Id",
                                "sClass": "center hidden"
                            },
                            {
                                "sName": "item1",
                                "sClass": "center",
                            },
                             {
                                 "sName": "itme2",
                                 "sClass": "center"
                             },                           
                        ]
                    }),
                }).always(function () {
                   oTable: $('#DataTable').dataTable({
                        "bAutoWidth": false,
                        cache: false,
                        "bServerSide": true,
                        "bDestroy": true,
                        "sAjaxSource": '@Url.Action("Action1", "Controller")',
                        "bProcessing": true,
                        "bJqueryUI": true,
                        "sPaginationType": "full_numbers",
                        "iDisplayLength": 5,
                        "aLengthMenu": [[5, 7, 10, 25, 50, -1], [5, 7, 10, 25, 50, "All"]],
                        "aaSorting": [[1, "desc"]],
                        "fnServerParams": function (aoData) {
                            aoData.push({ "name": "Job", "value": job });
                        },
                        "fnDrawCallback": function () {
                        },

                        "aoColumns": [
                            {
                                "sName": "Id",
                                "sClass": "center hidden"
                            },
                            {
                                "sName": "item1",
                                "sClass": "center",
                            },
                             {
                                 "sName": "itme2",
                                 "sClass": "center"
                             },                           
                        ]
                    }),
                }).always(function () {
                  oTable: $('#DataTable').dataTable({
                        "bAutoWidth": false,
                        cache: false,
                        "bServerSide": true,
                        "bDestroy": true,
                        "sAjaxSource": '@Url.Action("Action1", "Controller")',
                        "bProcessing": true,
                        "bJqueryUI": true,
                        "sPaginationType": "full_numbers",
                        "iDisplayLength": 5,
                        "aLengthMenu": [[5, 7, 10, 25, 50, -1], [5, 7, 10, 25, 50, "All"]],
                        "aaSorting": [[1, "desc"]],
                        "fnServerParams": function (aoData) {
                            aoData.push({ "name": "Job", "value": job });
                        },
                        "fnDrawCallback": function () {
                        },

                        "aoColumns": [
                            {
                                "sName": "Id",
                                "sClass": "center hidden"
                            },
                            {
                                "sName": "item1",
                                "sClass": "center",
                            },
                             {
                                 "sName": "itme2",
                                 "sClass": "center"
                             },                           
                        ]
                    })
                })
            })(jQuery);
});

Server side function to return output for each ajax hit and return output.

 public class JqueryDataTableModel
    {
        /// 
        /// Request sequence number sent by DataTable,
        /// same value must be returned in response
        /// 
        public string sEcho { get; set; }

        /// 
        /// Text used for filtering
        /// 
        public string sSearch { get; set; }

        /// 
        /// Number of records that should be shown in table
        /// 
        public int iDisplayLength { get; set; }

        /// 
        /// First record that should be shown(used for paging)
        /// 
        public int iDisplayStart { get; set; }

        /// 
        /// Number of columns in table
        /// 
        public int iColumns { get; set; }

        /// 
        /// Number of columns that are used in sorting
        /// 
        public int iSortingCols { get; set; }

        /// 
        /// Comma separated list of column names
        /// 
        public string sColumns { get; set; }

        public string Job { get; set; }
    }
 public ActionResult Action1(JqueryDataTableModel param)
        {
            int totalrecords = 0;
            string _job = param.Job;
            IEnumerable result = null;
            var sortDirection = Request["sSortDir_0"];//asc or desc
            var sortColumnIndex = Convert.ToInt32(Request["iSortCol_0"]);//Get Sorting Index of Column
            //var getCourseList = ArticleService.GetAllArticles(CourseId, param.sSearch, sortColumnIndex, sortDirection, param.iDisplayStart, param.iDisplayLength);
            IEnumerable _WIPJobDetails;
            using (var objWorkTicket = new WorkTicketEntities())
            {
                //Revenue work in progress
                _WIPJobDetails = objWorkTicket.sp_GetWIPRevenueBy_JobId(_job).ToList().OrderBy(x => x.TicketDate);
                if (!string.IsNullOrEmpty(param.sSearch)) //search as per work ticket
                {
                    _WIPJobDetails = _WIPJobDetails.Where(c => c.WorkTicket != null && c.WorkTicket.ToLower().Contains(param.sSearch.ToLower()));
                }
                if (sortColumnIndex == 1)//job#
                {
                    if (sortDirection == "desc")
                    {
                        //Run if sort direction is Descending
                        _WIPJobDetails = _WIPJobDetails.OrderByDescending(a => a.Job);
                    }
                    else if (sortDirection == "asc")
                    {
                        //Run if sort direction is Ascending
                        _WIPJobDetails = _WIPJobDetails.OrderBy(a => a.Job);
                    }
                }
                if (param.iDisplayLength != -1)
                    _WIPJobDetails = _WIPJobDetails.Skip(param.iDisplayStart).Take(param.iDisplayLength);
                var resultdata = (from c in _WIPJobDetails
                                  select new sp_GetWIPRevenueBy_JobId_Result
                                  {
                                      Job = c.Job,
                                      WorkTicket = c.WorkTicket,
                                      TicketDate = c.TicketDate,
                                   }).ToList();

                totalrecords = objWorkTicket.sp_GetWIPRevenueBy_JobId(_job).ToList().OrderBy(x => x.TicketDate).Count();
                result = from c in resultdata select new[] { Convert.ToString(c.Job), Convert.ToString(c.WorkTicket), Convert.ToString(c.TicketDate) };
                return Json(new
                {
                    sEcho = param.sEcho,
                    iTotalRecords = totalrecords,
                    iTotalDisplayRecords = totalrecords,
                    aaData = result,
                },
                JsonRequestBehavior.AllowGet);
            }
        }

If need any help feel free to contact me.

Other Links:-
More About Jquery Datatables

happy Coding..

Posted by | View Post | View Group