DataTables.net Export Button not generating Excel file - c#

I am getting the following error when I click on Export button of Datatables.net.
Following is my code
$.ajax({
type: "POST",
url: uri,
data: JSON.stringify(args),
contentType: "application/json;charset=utf-8",
success: function (data, status, xhr) {
//alert("The result is : " + data);
if (!data.d) {
$("#gvCurr").DataTable();
}
else {
$("#gvCurr").DataTable({
"aaData": JSON.parse(data.d),
"bDestroy": true,
dom: 'Bfrtip',
deferRender: true,
"bLengthChange": false,
"bPaginate": false,
buttons: [
{
extend: 'excel',
text: '<i class="fas fa-file-excel"></i> Export',
className: "btn btn-primary",
filename: 'DomesticInvoiceReport - ' + moment().format("DD-MMM-YYYY"),
}
],
"columns": [
{ "data": "ProjectNo" },
{ "data": "CountryName" },
{ "data": "StateName" },
{ "data": "SectorName" },
{ "data": "CoOrdName" },
{ "data": "Curr1" },
{ "data": "InvoiceNo_1" },
{ "data": "InvoiceDate_1" },
{ "data": "Month_1" },
{ "data": "Year_1" },
{ "data": "TotalFee_1" },
{ "data": "EscalationAmt_1" },
{ "data": "CurrentOPEAmt_1" },
{ "data": "CGSTPerc" },
{ "data": "SGSTPerc" },
{ "data": "TotalTaxPerc_1" },
{ "data": "TotalTaxAmt_1" },
{ "data": "CurrentInvoiceAmt_1" },
{
mRender: function (data, type, row) {
if (row.IsWithheld_1 == "" || row.IsWithheld_1 == 0)
return 'No';
}
},
{ "data": "WithheldAmt_1" },
{ "data": "BalanceInHandUptoThisInv_1" }
],
"order": [[0, "asc"]]
});
}
$("#entry").hide();
$("#list").show();
},
error: function (xhr) {
alert(xhr.responseText);
}
});
if you see int the code, If i comment out the columns after { "data": "Year_1" }, it is generating excel file and if I include the columns after that, it gives me error shown in the image attached. So it is not an issue of incorrect code or incorrect sequence of js files
I have included these settings in web.config
<httpRuntime targetFramework="4.7.2" maxRequestLength="2147483647" requestLengthDiskThreshold="2097152" executionTimeout="240" />
<jsonSerialization maxJsonLength="2147483644" />
It shows the records properly when retrieved. At the time of export it is giving error. I am not sure what am I missing here.

I believe you have this issue :
{
mRender: function (data, type, row) {
if (row.IsWithheld_1 == "" || row.IsWithheld_1 == 0)
return 'No';
}
},
render callbacks apply to the column definition, they cannot stay alone
You must return a value, if you return undefined you'll get "trim is not a function"
The correct way is
{
data: "IsWithheld_1",
render: function(data, type, row) {
return (data === '' || data == 0) ? 'No' : ''
}
}

Related

Parameter string is null when passed to controller from datatable

I am new in MVC. So this might be a stupid question from me.
I am trying to send parameter to my controller, but i did not get the value. Can someone help me what did i do wrong?
The username that is passed in the controller is always null. From the example that i follow it is using integer as the parameter. When i use id i will get the parameter. But when i pass string then i will get null value. Please help me. Thank you.
Here is the view
$(document).ready(function () {
dataTable = $("#batchTable").DataTable({
"ajax": {
"url": "/Home/GetDPUserList",
"type": "POST",
"datatype": "json"
},
"columns": [
{ "data": "Username", "name":"Username" },
{ "data": "Name", "name": "Name" },
{ "data": "Email", "name": "Email" },
{ "data": "IsAdmin", "name": "IsAdmin" },
{
"data": "Username", "render": function (data) {
return "<a class='btn btn-default btn-sm' onclick=EditUserForm('#Url.Action("UpdateUser","Home")/" + data +"')><i class='fa fa-pencil'></i> Edit</a><a class='btn btn-danger btn-sm' style='margin-left: 5px' onclick=Delete(" + data +")><i class='fa fa-trash'></i> Delete</a>";
},
"orderable": false,
"searchable": false,
"width": "150px"
},
],
"processing": "true",
"serverSide": "true",
"order": [0, "asc"]
});
});
function EditUserForm(url) {
alert(url)
var formDiv = $('<div/>');
$.get(url)
.done(function (response) {
formDiv.html(response);
popup = formDiv.dialog({
autoOpen: true,
resizable: false,
title: "Add New User",
height: 410,
width: 300,
close: function () {
popup.dialog('destroy').remove();
}
});
});
}
Here is the controller
[HttpGet]
public ActionResult UpdateUser(string username = "")
{
if (string.IsNullOrEmpty(username))
{
return View(new DP_User());
}
else
{
using (DBModel db = new DBModel())
{
return View(db.DP_User.Where(x => x.Username == username).FirstOrDefault<DP_User>());
}
}
}
Add route in Route.Config
routes.MapRoute(
name: "namesomething",/// as per your naming convention
url: "Home/UpdateUser/{username}",
defaults: new { controller = "Home", action = "UpdateUser", username = UrlParameter.Optional }
);

implement datatable js in Asp.Net API server side processing

I'm using datatable.js, I have table in view and API returns JSON results. I have lots of rows and i want to bind them by each page.Is there any way that datatable do it for me? I read lots of documentation but I didn't find anything useful for API
API Controller
public IHttpActionResult Get(int id)
{
return Ok(_context.Students.OrderBy(c => c.id).Skip((id - 1) * 10).Take(10).ToList());
}
Here is my table config
<script>$(document).ready(function () {
var pageindex = 1;
var table = $("#staff").DataTable({
"processing": true,
"serverSide": true,
ajax: {
url: "/Api/staffs",
dataSrc: "",
data: {
id: pageindex,
},
},
columns: [
{
data: "stf_FirstName",
},
{
data: "stf_LastName",
},
{
data: "stf_Code",
}
]
});
table.on('page', function () {
Currentpagenum();
});
function Currentpagenum() {
var info = table.page.info();
pageindex = (info.page + 1);
}
});</script>
If there are lots of rows than server side processing should be used
Try this :
HTML :
<table id="tblGrid" class="table display nowrap" style="width:100%">
</table>
JS :
function SetGrid() {
$('#tblGrid').DataTable({
"proccessing": true,
"serverSide": true,
// server side
"ajax": {
url: "/api/YourController/Method",
type: 'POST',
"data": {
Param1: Value1
}
},
// if client side
//data: YourList, // Js Array
columns: [
{ data: 'Id' },
{ data: 'Name', title: "Name" },
...
...
{ title: "Actions"},
],
"columnDefs": [
{ targets: 0, visible: false,},
],
"ordering": false,
"lengthChange": false,
"pageLength": 10,
"bDestroy": true,
"oLanguage": {
"sEmptyTable": "No Record Found"
},
});
}
Sample C# :
public object YourMethod(Param1 Value1)
{
var start = int.Parse(HttpContext.Current.Request.Form["start"]);
var result = new {
draw = HttpContext.Current.Request.Form["draw"],
recordsTotal = YourList.Count,
recordsFiltered = YourList.Count,
data = YourList.Skip(start).Take(10).ToList()
};
return result;
}

Ajax response not displaying on datatable while viewing on Firefox and Edge browsers

I have i report that displays fine on Google chrome, but while trying to view on Firefox or Edge browser, the json response displays on the browser instead of the datatable. Sample response below:
"
[{\"RegisteredBy\":\"Admin\",\"PatientRegNo\":\"De723\",\"PaymentType\":\"Cash\"}]"
I have tried including the below code:
contentType: 'application/json, charset=utf-8',
return Json(data,JsonRequestBehavior.AllowGet);
This is my Ajax function:
$("#searchBtn").click(function () {
var url = $("#frmReport").attr('action');
var str = $("#frmReport").serialize();
$("#searchBtn").prop("disabled", true);
$.ajax({
url: url,
type: "POST",
data: str,
cache: false,
dataType: "json",
success: function (_data) {
var arr = $.map(JSON.parse(_data), function (el) { return el });
table.clear();
table.destroy();
$('#tblReport').dataTable({
data: arr,
columns: [
{ "data": "RegisteredBy"},
{ "data": "PatientRegNo"},
{ "data": "PaymentType"},
],
dom: 'Bfrtip',
buttons: [
'copy', 'csv', 'excel',
{
extend: 'pdfHtml5',
orientation: 'portrait',
pageSize: 'A4'
}
]
});
}
});
table = $("#tblReport").DataTable();
});
});
My JsonResult Code:
getEntries = superAdminForBillingRepository.GetByRegNoOnly(regNo);
var data = Newtonsoft.Json.JsonConvert.SerializeObject(getEntries);
return Json(data);
I want to be able to view the ajax response on the datatable on any browser
try to invoke your table like this:
var tableTypeOfClientInfo = $('#tableTypeOfClientInfo ').DataTable({
"destroy": true,
"responsive":{
"details": {
renderer: function ( api, rowIdx, columns ) {
var data = $.map( columns, function ( col, i ) {
return col.hidden ?
'<tr data-dt-row="'+col.rowIndex+'" data-dt-column="'+col.columnIndex+'">'+
'<td>'+col.title+':'+'</td> '+
'<td>'+col.data+'</td>'+
'</tr>' :
'';
} ).join('');
return data ?$('<table/>').append( data ) :false;
}
}
},
"autoWidth": false,
"ajax": {
"url": 'some.php',
"method": 'POST',
data:{action:"SLC", categoryId:id}
},
"columns": [
{"data": "identification_number"},
{"data": "address"},
{"data": "birthday"},
{"data": "phone"},
{"data": "mail"}
],
"language":{"url": "//cdn.datatables.net/plug-ins/1.10.15/i18n/Spanish.json"},
"columnDefs": [
{
"className": "dt-center", "targets": "_all"
}
]
});

DataTable not showing JSON data

var table = $('#datatables').DataTable({
ajax: {
url: '#Url.Action("GetGrid","Vibrant", new { Area = "Marketing" })',
type: 'GET',
data: {
//filters here
columns: null,
filter: function () { return _filter; },
},
success: function (data) {
console.log("success", data);
},
error: function (data) {
console.log("error", data);
}
},
processing: true,
serverSide: true,
responsive: true,
pagingType: 'full_numbers',
language: {
search: "_INPUT_",
searchPlaceholder: "Search records",
},
columns: [
{ "data": "ID"},
{ "data": "PreviewID"},
{ "data": "EPCElement"},
{ "data": "Vibrant"}
],
method successfully returns data but the DataTable won't display it.
initialList = (from pjob in _db.PropertyJobs
select new SendVibrantOrderGridVM
{
ID = pjob.ID,
PreviewID = pjob.PreviewID,
EPCElement = pjob.EPCElement ,
Vibrant = pjob.Vibrant
}).ToList();
I am trying to populate my DataTable with the JSON Data I'd be getting within a call method.
This is a sample data returned by the GetGrid method:
{"data":[{"ID":529,"PreviewID":999992349,"EPCElement":false,"Vibrant":false}],"draw":1,"page":1,"pages":113,"length":10,"recordsTotal":1126,"recordsFiltered":1126}

datatable js ajax pass variable to C# serverside method

I have a datatable that is being populated via serverside ajax. I need to pass variables to the serverside C# method. The variables are not getting to the serverside.
I've tried a few different approaches. It should be pretty easy.
var tblApplication = $('#tblApplication').DataTable({
"ajax": {
"url": '../../Search/ApplicationList',
"type": 'POST',
"data":{
yearh: 2014,
make: ''
}
},
"autoWidth": false,
"fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
$(nRow).addClass("parent");
return nRow;
},
"order": [[1, "desc"]],
"deferRender": true,
"columns": [
{
"title": '',
"class": 'details-control',
"orderable": false,
"data": null,
"defaultContent": '<img src="../../assets/images/details_open.png" />'
},
{ "title": 'ApplicationId', "data": 'ApplicationId', "visible": false },
{ "title": 'Year', "data": 'Year' },
{ "title": 'Make', "data": 'Make' },
{ "title": 'Model', "data": 'Model' },
{ "title": 'Qualifier', "data": 'Qualifier' },
{ "title": 'Axle', "data": 'Axle' },
{ "title": 'Pad Set', "data": 'PadSet' },
{ "title": 'Side', "data": 'Side' },
{ "title": 'Part List', "data": 'PartListId' }
]
});
[HttpPost]
public JsonResult ApplicationList(int year = 0, string make = null )
{
}
According to datatables.js reference you need to extend "data" something like following to make it work;
$('#example').dataTable( {
"ajax": {
"url": "data.json",
"data": function ( d ) {
return $.extend( {}, d, {
"extra_search": $('#extra').val(),
"year": 2014,
"make": 'Nissan'
} );
}
}
} );
For further documentation please see the this. Hope this helps.

Categories

Resources