Loading the datatable with the data from JsonResult method from the controller, makes alignment fails in footer - datatables

I am trying to find the total of 'Net Value' and ' Total Value' in datatable as footer and the total value should be shown inside td element with the same alignment of its other data column. If I try to add footer , the total column shows different position from its data column. The footer should be showed the same column of its data. Here is my code in html. Since I am not able to show the original program , I had to make it in presentable format.
I am showing the data by calling JsonResult method from the controller , But after fetching the data from the Json method and showing the result in datatable with vertical scrolling, the footer value is showed bit far from its data column
#model myModel
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.2/css/jquery.dataTables.min.css" />
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.3.4/css/buttons.dataTables.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/1.13.2/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.3.4/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.3.4/js/buttons.html5.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>
</head>
<body>
<table id="myTable" class="table table-bordered table-striped" style="width:100%;font-size:90%">
<thead>
<tr>
<th>
Item
</th>
<th>
Net Value
</th>
<th>
Total Value
</th>
</tr>
</thead>
<tbody id="body">
<tr>
<td>Item</td>
<td>NetVal</td>
<td>TotVal</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Total</td>
<td></td>
<td></td>
</tr>
</tfoot>
</table>
<script>
$(document).ready(function () {
var report = {};
report.FromDate = "#Model.FromDate";
report.ToDate = "#Model.ToDate";
report.CustomerCode = "#Model.CustomerCode";
var table = $('#myTable').DataTable({
"processing": true,
"ajax": {
"url": "/mySales/SalesData",
"data": report,
"dataSrc": function (json) {
console.log(json);
return JSON.parse(json);
}
},
"columns": [
{ "data": "Item" },
{ "data": "NetVal" },
{ "data": "TotVal" },
],
"columnDefs": [
{
"className": "dt-center", "targets": "_all"
},
{ "width": "10%", "targets": 0 },
{ "width": "5%", "targets": 1 },
{ "width": "5%", "targets": 2 },
],
"pageLength": 40,
scrollY: "500px",
scrollX: true,
paging: true,
footerCallback: function (row, data, start, end, display) {
var api = this.api(), data;
var intVal = function (i) {
return typeof i === 'string' ?
i.replace(/[\$,]/g, '') * 1 :
typeof i === 'number' ?
i : 0;
};
var col1 = api
.column(1)
.data()
.reduce(function (a, b) {
return intVal(a) + intVal(b);
}, 0);
var col2 = api
.column(2)
.data()
.reduce(function (a, b) {
return intVal(a) + intVal(b);
}, 0);
$(api.column(1).footer()).html(col1);
$(api.column(2).footer()).html(col1);
},
scrollCollapse: true,
dom: 'Bfrtip',
buttons: [
'copyHtml5',
'excelHtml5',
'csvHtml5',
'pdfHtml5'
]
})
})
</script>
// Controller
public JsonResult SalesData(myModel model)
{
DateTime fromDate = new DateTime();
DateTime toDate = new DateTime();
if (report.FromDate != "" && report.ToDate != "" && report.FromDate != null && report.ToDate != null)
{
fromDate = DateTime.ParseExact(report.FromDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
toDate = DateTime.ParseExact(report.ToDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
}
report.CustomerCode = "001";
var data = _unitOfWork.GetSummary(report.CustomerCode, fromDate, toDate);
String jsonResult = JsonConvert.SerializeObject(data);
return Json(jsonResult);
}

Related

Create the footer in Data Table and to Export it with its footer into Excel and PDF

I am trying to find the total of 'Net Value' and ' Total Value' in datatable as footer and the total value should be shown inside td element with the same alignment of its other data column. If I try to add footer , the total column shows different position from its data column also How can I find the total value and how to show it in footer row corresponding the column of its data row. Here is my code in html. Since I am not able to show the original program , I had to make it in presentable format. I am showing the data by calling JsonResult method from the controller , After fetching the data from the method and showing the report, the footer value will be showing bit far from its data column
#model myModel
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.2/css/jquery.dataTables.min.css" />
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.3.4/css/buttons.dataTables.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/1.13.2/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.3.4/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.3.4/js/buttons.html5.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>
</head>
<body>
<table id="myTable" class="table table-bordered table-striped" style="width:100%;font-size:90%">
<thead>
<tr>
<th>
Item
</th>
<th>
Net Value
</th>
<th>
Total Value
</th>
</tr>
</thead>
<tbody id="body">
<tr>
<td>Item</td>
<td>NetVal</td>
<td>TotVal</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Total</td>
<td></td>
<td></td>
</tr>
</tfoot>
</table>
<script>
$(document).ready(function () {
var report = {};
report.FromDate = "#Model.FromDate";
report.ToDate = "#Model.ToDate";
report.CustomerCode = "#Model.CustomerCode";
var table = $('#myTable').DataTable({
"processing": true,
"ajax": {
"url": "/mySales/SalesData",
"data": report,
"dataSrc": function (json) {
console.log(json);
return JSON.parse(json);
}
},
"columns": [
{ "data": "Item" },
{ "data": "NetVal" },
{ "data": "TotVal" },
],
"columnDefs": [
{
"className": "dt-center", "targets": "_all"
},
{ "width": "10%", "targets": 0 },
{ "width": "5%", "targets": 1 },
{ "width": "5%", "targets": 2 },
],
"pageLength": 40,
scrollY: "500px",
scrollX: true,
paging: true,
footerCallback: function (row, data, start, end, display) {
var api = this.api(), data;
var intVal = function (i) {
return typeof i === 'string' ?
i.replace(/[\$,]/g, '') * 1 :
typeof i === 'number' ?
i : 0;
};
var col1 = api
.column(1)
.data()
.reduce(function (a, b) {
return intVal(a) + intVal(b);
}, 0);
var col2 = api
.column(2)
.data()
.reduce(function (a, b) {
return intVal(a) + intVal(b);
}, 0);
$(api.column(1).footer()).html(col1);
$(api.column(2).footer()).html(col1);
},
scrollCollapse: true,
dom: 'Bfrtip',
buttons: [
'copyHtml5',
'excelHtml5',
'csvHtml5',
'pdfHtml5'
]
})
})
</script>
/
/ Controller
public JsonResult SalesData(myModel model)
{
DateTime fromDate = new DateTime();
DateTime toDate = new DateTime();
if (report.FromDate != "" && report.ToDate != "" && report.FromDate != null && report.ToDate != null)
{
fromDate = DateTime.ParseExact(report.FromDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
toDate = DateTime.ParseExact(report.ToDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
}
report.CustomerCode = "001";
var data = _unitOfWork.GetSummary(report.CustomerCode, fromDate, toDate);
String jsonResult = JsonConvert.SerializeObject(data);
return Json(jsonResult);
}
You could try scrollCollapse: true to set the footer to the right position,add a fallbackfunction to calculate the total value ,and check this demo related with export button if you missed to refer the js/css files
I tried as below:
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.2/css/jquery.dataTables.min.css" />
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.3.4/css/buttons.dataTables.min.css" />
<div>
<table id="myTable" class="table table-bordered table-striped" style="width:100%;font-size:90%">
<thead>
<tr>
<th>
Item
</th>
<th>
Net Value
</th>
<th>
Total Value
</th>
</tr>
</thead>
<tbody id="body">
<tr>
<td>AAA</td>
<td>200.00</td>
<td>300.00</td>
</tr>
<tr>
<td>BBB</td>
<td>300.00</td>
<td>200.00</td>
</tr>
<tr>
<td>CCC</td>
<td>300.00</td>
<td>200.00</td>
</tr>
<tr>
<td>DDD</td>
<td>300.00</td>
<td>200.00</td>
</tr>
<tr>
<td>EEE</td>
<td>300.00</td>
<td>200.00</td>
</tr>
<tr>
<td>FFF</td>
<td>300.00</td>
<td>200.00</td>
</tr>
<tr>
<td>GGG</td>
<td>300.00</td>
<td>200.00</td>
</tr>
<tr>
<td>HHH</td>
<td>300.00</td>
<td>200.00</td>
</tr>
<tr>
<td>III</td>
<td>300.00</td>
<td>200.00</td>
</tr>
</tbody>
<tfoot>
<tr>
<th>Total</th>
<td></td>
<td></td>
</tr>
</tfoot>
</table>
</div>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.13.2/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.3.4/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.3.4/js/buttons.html5.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>
$(document).ready(function () {
var table = $('#myTable').DataTable({
"pageLength": 40,
scrollY: "500px",
scrollX: true,
paging: true,
footerCallback: function (row, data, start, end, display) {
var api = this.api(), data;
var intVal = function (i) {
return typeof i === 'string' ?
i.replace(/[\$,]/g, '') * 1 :
typeof i === 'number' ?
i : 0;
};
var col1 = api
.column(1)
.data()
.reduce(function (a, b) {
return intVal(a) + intVal(b);
}, 0);
var col2 = api
.column(2)
.data()
.reduce(function (a, b) {
return intVal(a) + intVal(b);
}, 0);
$(api.column(1).footer()).html(col1);
// Here you can add the rows
$(api.column(2).footer()).html(col2);
},
scrollCollapse: true,
dom: 'Bfrtip',
buttons: [
'copyHtml5',
'excelHtml5',
'csvHtml5',
'pdfHtml5'
]
})
})
</script>
The result:

My datatable is not picking the json result

I am using datatables and my get handler returns a json result but the datatable is not displaying it. What am I missing? Here's my code. I am using Visual Studio 2019 3.1 .net core with razor pages. I am trying to call my datatable in the OnGet handler. I tried the post but that did not work either.
My cust class:
public class Cust
{
public int Id { get; set; }
public string Name { get; set; }
public string PhoneNumber { get; set; }
public string Address { get; set; }
public string PostalCode { get; set; }
}
_layout.cshtml:
<div class="container">
<main role="main" class="pb-3">
#RenderBody()
</main>
</div>
<footer class="border-top footer text-muted">
<div class="container">
© 2022 - testApp - <a asp-area="" asp-page="/Privacy">Privacy</a>
</div>
</footer>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.12.1/datatables.min.css" />
<script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.12.1/datatables.min.js"></script>
#RenderSection("Scripts", required: false)
My Index.cshtml.cs model code:
public class IndexModel : PageModel
{
[BindProperty]
public int Draw { get; set; }
// public IEnumerable<Column> Columns { get; set; }
// public IEnumerable<Order> Order { get; set; }
public int Start { get; set; }
public int Length { get; set; }
public List<Cust> Customers = new List<Cust>();
public JsonResult OnGet()
{
var recordsTotal = 3;
Cust cs1 = new Cust();
cs1.Id = 1;
cs1.Name = "test1";
cs1.Address = "address1";
cs1.PhoneNumber = "11111";
cs1.PostalCode = "1111";
Cust cs2 = new Cust();
cs2.Id = 1;
cs2.Name = "test2";
cs2.Address = "address1";
cs2.PhoneNumber = "11111";
cs2.PostalCode = "1111";
Cust cs3 = new Cust();
cs3.Id = 1;
cs3.Name = "test3";
cs3.Address = "address1";
cs3.PhoneNumber = "11111";
cs3.PostalCode = "1111";
Customers.Add(cs1);
Customers.Add(cs2);
Customers.Add(cs3);
var recordsFiltered = Customers.Count();
var data = Customers;
return new JsonResult(new
{
Draw = Draw,
RecordsTotal = recordsTotal,
RecordsFiltered = recordsFiltered,
Data = data
});
}
My Razor page -- Pages/customers/Index.cshtml:
#page
#model testApp.Pages.Customer.IndexModel
#{
}
<h1>Index</h1>
<p>
</p>
<table id="myTable" class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Customers[0].Id)
</th>
<th>
#Html.DisplayNameFor(model => model.Customers[0].Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Customers[0].PhoneNumber)
</th>
<th>
#Html.DisplayNameFor(model => model.Customers[0].Address)
</th>
<th>
#Html.DisplayNameFor(model => model.Customers[0].PostalCode)
</th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
#section Scripts {
<script>
$(document).ready(function () {
$('#myTable').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
url: "/customers/Index?handler=OnGet",
"type": "GET",
"dataType": "json"
},
"columns": [
{ "data": "id", "autowidth": true },
{ "data": "name", "autowidth": true },
{ "data": "phoneNumber", "autowidth": true },
{ "data": "address", "autowidth": true },
{ "data": "postalCode", "autowidth": true }
],
"order": [[0, "desc"]]
});
});
</script>
}
Here's my json response.
{
"draw": 0,
"recordsTotal": 3,
"recordsFiltered": 3,
"data": [
{
"id": 1,
"name": "test1",
"phoneNumber": "11111",
"address": "address1",
"postalCode": "1111"
},
{
"id": 1,
"name": "test2",
"phoneNumber": "11111",
"address": "address1",
"postalCode": "1111"
},
{
"id": 1,
"name": "test3",
"phoneNumber": "11111",
"address": "address1",
"postalCode": "1111"
}
]
}
I am just testing it with this project to see if I can get the datatable to work. I will be eventually getting the data from the database. Yes, the volume will be big, thousands of rows.
Here is a whole working demo you could follow:
Page(Pages/customers/Index.cshtml)
#page
#model IndexModel
<h1>Index</h1>
<p>
</p>
<table id="myTable" class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Customers[0].Id)
</th>
<th>
#Html.DisplayNameFor(model => model.Customers[0].Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Customers[0].PhoneNumber)
</th>
<th>
#Html.DisplayNameFor(model => model.Customers[0].Address)
</th>
<th>
#Html.DisplayNameFor(model => model.Customers[0].PostalCode)
</th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
JS in page:
#section Scripts {
<script>
$(document).ready(function () {
$.ajax({
type: "GET",
url: "/customers/Index?handler=Json", //change here...
dataType: "json",
success: OnSuccess,
});
});
function OnSuccess(response) {
console.log(response.data)
$('#myTable').DataTable(
{
data: response.data,
columns: [
{ "data": "id" },
{ "data": "name" },
{ "data": "phoneNumber" },
{ "data": "address" },
{ "data": "postalCode" }
],
});
};
</script>
}
PageModel(Pages/customers/Index.cshtml.cs):
public class IndexModel : PageModel
{
[BindProperty]
public int Draw { get; set; }
// public IEnumerable<Column> Columns { get; set; }
// public IEnumerable<Order> Order { get; set; }
public int Start { get; set; }
public int Length { get; set; }
public List<Cust> Customers = new List<Cust>();
public void OnGet() //add this.....
{
}
public JsonResult OnGetJson() //change handler name..
{
var recordsTotal = 3;
Cust cs1 = new Cust();
cs1.Id = 1;
cs1.Name = "test1";
cs1.Address = "address1";
cs1.PhoneNumber = "11111";
cs1.PostalCode = "1111";
Cust cs2 = new Cust();
cs2.Id = 1;
cs2.Name = "test2";
cs2.Address = "address1";
cs2.PhoneNumber = "11111";
cs2.PostalCode = "1111";
Cust cs3 = new Cust();
cs3.Id = 1;
cs3.Name = "test3";
cs3.Address = "address1";
cs3.PhoneNumber = "11111";
cs3.PostalCode = "1111";
Customers.Add(cs1);
Customers.Add(cs2);
Customers.Add(cs3);
var recordsFiltered = Customers.Count();
var data = Customers;
return new JsonResult(new
{
Draw = Draw,
RecordsTotal = recordsTotal,
RecordsFiltered = recordsFiltered,
Data = data
});
}
}
_Layout.cshtml:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>#ViewData["Title"] - RazorPagesProj3_1</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" />
</head>
<body>
<header>
//....
</header>
<div class="container">
<main role="main" class="pb-3">
#RenderBody()
</main>
</div>
<footer class="border-top footer text-muted">
<div class="container">
© 2022 - RazorPagesProj3_1 - <a asp-area="" asp-page="/Privacy">Privacy</a>
</div>
</footer>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.12.1/datatables.min.css" />
<script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.12.1/datatables.min.js"></script>
#RenderSection("Scripts", required: false)
</body>
</html>

Asp.net core Razor Page - JQ data table not load data

I have an Asp.net core project with Razor Page ,I try to implement a JQ data table but the data not load.
Here is the Javascript code:
$('#dataList').DataTable({
// "iDisplayLength": 100,
// "sPaginationType": "full_numbers",
processing: true,
serverSide: true,
ajax: {
async: true,
type: "POST",
contentType: "application/json; charset=utf-8",
url: '/CoursesDP/?handler=Data',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: function (d) {
// note: d is created by datatable, the structure of d is the same with DataTableParameters model above
// console.log(JSON.stringify(d));
return JSON.stringify(d);
},
success: function (r) {
console.log(r);
}
},
})
I write the data is coming to console:
{"draw":1,"recordsTotal":11,"recordsFiltered":11,"data":[["oooo"],["ccc"],["aaa"],["pppp"],["pppp"],["yyy"],["12"],["pppp"],["pppp"],["pppp"],["fff"]]}
This is the html code:
<table id="dataList" class="display" style="width:100%">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.CourseDP[0].CourseName)
</th>
</tr>
</thead>
but the data not load to the data table .
What can I do?
The following is a working sample using DataTables with testing data, you can refer to it.
CoursesDP.cshtml:
#page
#model ModelValidation_MVC_.Pages.CourseDB.CoursesDPModel
#{
ViewData["Title"] = "CoursesDP";
}
<h1>CourseDP</h1>
<div>
<table id="dataList" class="table table-striped table-bordered" style="width:100%">
<thead class="thead-dark">
<tr class="table-info">
<th>id</th>
<th>name</th>
<th>age</th>
<th>phone</th>
<th>email</th>
</tr>
</thead>
</table>
</div>
#section scripts{
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.js"></script>
<script type="text/javascript">
$('#dataList').DataTable({
"processing": true,
"serverSide": true,
ajax: {
type: "POST",
url: '/CourseDB/CoursesDP/?handler=Data',
},
columns: [
{ data: 'id' },
{ data: 'name' },
{ data: 'age' },
{ data: 'phone' },
{ data: 'email' }
]
})
</script>
}
CoursesDP.cshtml.cs:
[IgnoreAntiforgeryToken]
public class CoursesDPModel : PageModel
{
public static List<TestDT> testDTs = new List<TestDT> { new TestDT {id=1, name = "TestDT1", age = 1, phone = "1", email = "TestDT1#.com" },
new TestDT {id=2, name = "TestDT2", age = 2, phone = "2", email = "TestDT2#.com" }, new TestDT {id=3, name = "TestDT3", age = 3, phone = "3", email = "TestDT3#.com" } ,
new TestDT {id=4, name = "TestDT4", age = 4, phone = "4", email = "TestDT4#.com" }, new TestDT {id=5, name = "TestDT5", age = 5, phone = "5", email = "TestDT5#.com" } ,
new TestDT {id=6, name = "TestDT6", age = 6, phone = "6", email = "TestDT6#.com" },new TestDT {id=7, name = "TestDT7", age = 7, phone = "7", email = "TestDT7#.com" },};
public static List<TestId> testIds = new List<TestId> { new TestId { id = 1 }, new TestId { id = 2 } };
public IActionResult OnGet()
{
return Page();
}
public JsonResult OnPostData()
{
Postdata postdata = new Postdata { draw = 1, recordsTotal =7, recordsFiltered = 7, data = testDTs };
return new JsonResult(postdata);
}
}
result:

jquery datatable does not get initialized with given response

I want to initialize data table with my generated response
my response looks like this
{data: Array(3), status: true}
data : Array(3)
0 : {countryId: 1, countryName: "sampleCountry", countryShortCode: "sampleCode", status: "yes"}
1 : {countryId: 2, countryName: "pakistan", countryShortCode: "pak", status: "yes"}
2 : {countryId: 3, countryName: "sample2", countryShortCode: "pak", status: "yes"}
please look at my html
<table class="table table-striped" id="countryTable">
<thead>
<tr>
<th>S.NO.</th>
<th>Country Name</th>
<th>Country Short Name</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
please look at my datatable initialization
$.ajax({
url : url,
type:"get",
contentType:'application/json; charset=utf-8',
dataType: 'json' ,
async: false,
success:function(response)
{
alert(response.data);
$('#countryTable').DataTable( {
"fnRowCallback" : function(nRow, aData, iDisplayIndex){
$("td:first", nRow).html(iDisplayIndex +1);
return nRow;
},
destroy: true,
mydata: response.data,
columns: [
{ mydata:'countryId'},
{ mydata:'countryName'},
{ mydata:'countryShortCode'}
]
} );
console.log(response);
}
});
after initialization data table shows as No data available in table but table gets initialized with datatable plugin .
data is not coming into table.
what went wrong in my code please help me.
The code looks fine, you just need to change mydata to data, like this:
var response = {
data: [{
countryId: 1,
countryName: "sampleCountry",
countryShortCode: "sampleCode",
status: "yes"
},
{
countryId: 2,
countryName: "pakistan",
countryShortCode: "pak",
status: "yes"
},
{
countryId: 3,
countryName: "sample2",
countryShortCode: "pak",
status: "yes"
}
],
status: true
}
$('#countryTable').DataTable({
"fnRowCallback": function(nRow, aData, iDisplayIndex) {
$("td:first", nRow).html(iDisplayIndex + 1);
return nRow;
},
destroy: true,
data: response.data,
columns: [{
data: 'countryId'
},
{
data: 'countryName'
},
{
data: 'countryShortCode'
}
]
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet" />
<table class="table table-striped" id="countryTable">
<thead>
<tr>
<th>S.NO.</th>
<th>Country Name</th>
<th>Country Short Name</th>
</tr>
</thead>
<tbody>
</tbody>
</table>

Datatables plugin for jQuery. How to hide rows? Export to Excel still showing hidden rows

I was able to figure out how to hide the rows I wanted using JQuery. I have a modal that pops out for the user deselects the checkbox on what rows they want to hide. It works perfectly but when I export it to excel it still displays the hidden rows. I am not using the API at all and I think that's my problem. I am hiding the rows by using .show() and .hide(). I am using the API to hide the columns and when I click my export to excel button it works just fine. Could anyone help me figure out how to hide rows and be able to export it to excel with the rows not showing on the spreadsheet?
HTML
<script type="text/javascript" language="javascript" src="https://cdn.datatables.net/buttons/1.2.4/js/dataTables.buttons.min.js">
</script>
<script type="text/javascript" language="javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/2.5.0/jszip.min.js">
</script>
<script type="text/javascript" language="javascript" src="https://cdn.datatables.net/buttons/1.2.4/js/buttons.html5.min.js">
</script>
<table cellpadding="0" cellspacing="0" border="0" class="dataTable" class="example">
<thead>
<tr>
<th>Item</th>
<th>Store 1</th>
<th>Store 2</th>
<th>Store 3</th>
<th>Store 4</th>
</tr>
</thead>
<tbody>
<tr>
<td>Sugar</td>
<td>21</td>
<td>95</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td>Coffee</td>
<td>5</td>
<td>41</td>
<td>5</td>
<td>1</td>
</tr>
<tr>
<td>Banana</td>
<td>123</td>
<td>323</td>
<td>22</td>
<td>233</td>
</tr>
<tr>
<td>Gum</td>
<td>13</td>
<td>213</td>
<td>2</td>
<td>33</td>
</tr>
<tr>
<td>Milk</td>
<td>23</td>
<td>24</td>
<td>44</td>
<td>242</td>
</tr>
</tbody>
</table>
</div>
</body>
JavaScript
var table = $('.example').DataTable({
dom: 'Bfrtip',
buttons: [
{
extend: 'excelHtml5',
exportOptions: {
columns: ':visible'
},
text: 'Export to Excel'
},
],
});
// I get the attribute name from the checkbox and I match it with the id on the row and when the checkbox is unchecked I hide the rows.
$('input.rowsHideSeek').click(function() {
var name = $(this).attr('name');
if ($(this).is(':checked')) {
$('#' + name).show()
} else {
$('#' + name).hide()
}
});
This is what I came up with and it seems to work. It shows and hides rows and, on export, only shows rows not hidden.
here is it is on jsbin http://jsbin.com/qituvu/edit?output
The key part is that it uses the customizeData in the extended excelHtml5.
$(document).ready(function () {
// this just creates a critera to filter on
var faketype = 1;
for (var i = 0; i < dataStore.data1.length; ++i) {
dataStore.data1[i].type = faketype++;
if (faketype == 5) faketype = 1;
}
var aTable = $('#example').DataTable({
"data": dataStore.data1,
paging:false,
"columns": [
{ "data": "name" },
{ "data": "position" },
{ "data": "office", className: "editColumn" },
{ "data": "extn" },
{ "data": "start_date" },
{ "data": "salary" },
{ "data": "type"}
], dom: 'Bfrti',
"createdRow": function( row, data, dataIndex ) {
$(row).addClass('type_' + data.type);
},
buttons: [{text:"Excel",
extend: 'excelHtml5', customizeData: function (exData) {
var rowNodes = aTable.rows().nodes();
var newData = []
for (var i = (exData.body.length - 1) ; i >= 0; i--) {
if ($(rowNodes[i]).css("display") == "none") {
continue;
}
newData[newData.length] = exData.body[i];
}
// the loop reverses order so put it back
exData.body = newData.reverse();
}}]
});
// event handler for hiding and showing rows
$("input[name='hideType']").on("click", function () {
var c = $(this).val();
var isChecked = $(this).prop('checked');
$(aTable.rows('.type_' + c).nodes()).toggle(isChecked);
aTable.rows().invalidate().draw();
});
});
The problem with jQuery hide() / show() is that you will need to tweak any part of dataTables you are using, if you want to fake persistent "hidden" rows.
Here is a few plug-in methods that provide real hide() and restore() on rows in dataTables :
$.fn.dataTableExt.hiddenRows = {};
$.fn.dataTable.Api.register( 'row.hide()', function(selector) {
var row = this.row(selector);
if (row.length == 0) return -1;
var index = row.node()._DT_RowIndex;
$.fn.dataTableExt.hiddenRows[index] = row.node().outerHTML;
row.remove().draw(false);
return index;
});
$.fn.dataTable.Api.register( 'row.restore()', function(index) {
var row = $.fn.dataTableExt.hiddenRows[index];
if (row) {
this.row.add( $(row) ).draw(false);
delete $.fn.dataTableExt.hiddenRows[index];
return true;
}
return false;
});
Now you have table.row.hide() and table.row.restore(). The methods use the dataTables API, and does nothing but maintaining a list of removed rows by their unique indexes. A demo could look like this :
var table = $('#example').DataTable({}) ;
$('#example').on('click', 'tbody tr', function() {
var index = table.row.hide(this);
var $button = $('<button></button>')
.addClass('restore')
.attr('index', index)
.text('show #'+index);
$('body').prepend($button);
})
$('body').on('click', '.restore', function() {
var index = $(this).attr('index');
table.row.restore(index);
$(this).remove();
})
When you click on a row it is hidden (i.e removed); a restore button is generated for each hidden row. If you click on the button the corresponding row is restored.
Demo -> http://jsfiddle.net/s183ek2q/