I'm trying to populate a table on a button click, getting the data from an ASP.NET ApiController. I've tried with almost all solutions posted in SO to other similar issues but always get that error.
Hope someone sees the problem.
The html markup:
<input type="button" ID="btnSearch" name="btnSearch" class="btn btn-success" value="Buscar" />
<table id="ResultsTable" class="table table-bordered table-condensed" style="font-size: 11px;">
<thead>
<tr>
<th><%=GetLiteral("Codigo")%></th>
<th><%=GetLiteral("Descripcion")%></th>
<th><%=GetLiteral("Marca")%></th>
<th><%=GetLiteral("IC")%></th>
<th><%=GetLiteral("IV")%></th>
<th><%=GetLiteral("Tarifa")%></th>
<th><%=GetLiteral("Precio")%></th>
<th><%=GetLiteral("P")%></th>
<th><%=GetLiteral("Total")%></th>
<th><%=GetLiteral("Central")%></th>
<th><%=GetLiteral("Centro")%></th>
</tr>
</thead>
<tbody>
</tbody>
The JS:
$(document).ready(function () {
var SearchTable = $("#ResultsTable").DataTable({
columns: [
{ data: "pCodigo" },
{ data: "rDescripcion" },
{ data: "rMarca" },
{ data: "xIndiceCarga" },
{ data: "xIndiceVelocidad" },
{ data: "TARIFA" },
{ data: "PRECIO" },
{ data: "PROVIENE" },
{ data: "TOTAL" },
{ data: "CENTRAL" },
{ data: "CENTRO" }
],
ordering: false,
searching: false
});
$("#btnSearch").click(function () {
var searchText = $("#<%=txtSearch.ClientID%>").val();
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: '<%=ResolveUrl("~/api/ProductSearch/")%>' + searchText + '/0138107',
dataType: "json"
}).success(function(result) {
SearchTable.clear().draw();
SearchTable.rows.add(result).draw();
}).fail(function(jqXHR, textStatus, errorThrown) {
alert("FAIL: " + textStatus + " = " + errorThrown);
});
});
}
A data sample:
[{
"RowError": "",
"RowState": 2,
"Table": [{
"pCodigo": "10006908",
"rDescripcion": "225/65/16-VAN100(112R)CO B-B-72-2",
"rMarca": "CONTI",
"xDibujo": 254176,
"xIndiceCarga": "112",
"xIndiceVelocidad": "R",
"xEje": 0,
"xAplicacion": 0,
"xDecimales": false,
"xTipoIVA": 2,
"xTasa": 2.550,
"TARIFA": 203.50,
"PRECIO": 105.54,
"PROVIENE": "LG",
"COLOR": 8454143,
"TOTAL": 3.00,
"CENTRAL": 2.00,
"CENTRO": 2.00,
"xControl": true
},
{
"pCodigo": "30000159",
"rDescripcion": "225/65/16-RF09(112R)ROTALLA E-C-73-3",
"rMarca": "ROTAL",
"xDibujo": 253405,
"xIndiceCarga": "112",
"xIndiceVelocidad": "R",
"xEje": 0,
"xAplicacion": 0,
"xDecimales": false,
"xTipoIVA": 2,
"xTasa": 2.550,
"TARIFA": 69.00,
"PRECIO": 49.29,
"PROVIENE": "LG",
"COLOR": 16777088,
"TOTAL": 89.00,
"CENTRAL": 55.00,
"CENTRO": 55.00,
"xControl": true
}],
"ItemArray": ["30000159",
"225/65/16-RF09(112R)ROTALLA E-C-73-3",
"ROTAL",
253405,
"112",
"R",
0,
0,
false,
2,
2.550,
69.00,
49.29,
"LG",
16777088,
89.00,
55.00,
55.00,
true],
"HasErrors": false
}]
Note: The GetLiteral function in html markup returns a string with the column name internationalized, that can be different from the text shown and column name. I think that's not the problem.
Thanks in advance!
You must insert the Table array :
}).success(function(result) {
SearchTable.clear().draw();
SearchTable.rows.add(result[0].Table).draw();
})
alternatively you can cycle through the Table array and add each item individually :
}).success(function(result) {
SearchTable.clear().draw();
for (var i=0;i<result.Table.length;i++) {
SearchTable.row.add(result[0].Table[i]).draw();
}
})
Related
This is my working cshtml with ajax. Currently $(function () { loaddata();}) is what initializes the DataTable and "url": '/LoadData'() posts to the controller. But I need it to Post only when validation passes. I still need the Datatable to initialize though. When the document is ready I would like to initialize the Datatable just not LoadData. Post should automatically happen when validation passes.
button onclick="test()">RefreshData</button>
<table id="tblList" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th>a</th>
<th>b</th>
<th>c</th>
<th>d</th>
</tr>
</thead>
</table>
js:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.css">
function test() {
$('#tblList').DataTable().ajax.reload();
}
function validationfailure() {
//$('#firstname').val()=="";
return 'please enter a valid name'
}
function loaddata() {
var data = {};
data.id = $("#id").val();
$('#tblList').DataTable({
destroy: true,
ajax: {
"type": "POST",
"url": '/LoadData',
"dataType": "json",
"data": function(d) {
d.id = $("#id").val();
}
},
columns: [
{ "data": "a", responsivePriority: 1, "searchable": true },
{ "data": "b", responsivePriority: 2, "searchable": true },
{ "data": "c", responsivePriority: 3, "searchable": true },
{ "data": "d", responsivePriority: 4, "searchable": true },
],
});
};
$(function() {
if(!validationfailure)
loaddata();
})
action:
[HttpPost]
[Route("LoadData")]
public IActionResult GetFinanceiro(SearchModel s)
{
List<DataTableModel> l = new List<DataTableModel> {
new DataTableModel{ a="a1"+s.Id,b="b1"+s.Id,c="c1"+s.Id,d="d1"+s.Id},
new DataTableModel{ a="a2",b="b2",c="c2",d="d2"},
new DataTableModel{ a="a3",b="b3",c="c3",d="d3"},
new DataTableModel{ a="a4",b="b4",c="c4",d="d4"},
};
return Json(new { data = l });
}
I am working on datatable .i want pagination on search for example i have a datatable with pagination . i have a search option but pagination does not work on search
<input class="btn btn-secondary" type="button" value="Show TheResults" id="theBtnSearch" />
$("#theBtnSearch").click(function () {
if ($.fn.dataTable.isDataTable('#thedatatab')) {
table = $('#thedatatab').DataTable();
//https://datatables.net/reference/api/ajax.reload()
table.ajax.reload();
}
});
<div class="DataTableClass" id="TheHeaderStyle" style="width: 100%">
<table id="thedatatab'" class="display table table-striped table-bordered">
<thead>
<tr>
<th><%: Html.DisplayNameFor(r => r.fieldA)%></th>
<th><%: Html.DisplayNameFor(r => r.fieldB)%></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
The method that gets called into
public JsonResult GetTheData(DTParameters param)
{
try
{
//call stored procedure with parms from DTParameters
//DTParameters comes with your datatables download, if you did it right
return Json(result);
}
}
Your DataTable declaration
$('#thedatatab').DataTable({
"pagingType": "full",
"serverSide": true,
"oLanguage": {
"sSearch": "Filter Search Results:" //http://legacy.datatables.net/usage/i18n#oLanguage.sSearch
},
"ajax": {
"type": "POST",
"url": '/Case/GetTheData',
"contentType": 'application/json; charset=utf-8',
'data': function (data) {
//http://stackoverflow.com/questions/24499116/how-to-pass-parameters-on-reload-of-datatables
//all the search parms here
data.searchParm = $("#searchParm").val();
return data = JSON.stringify(data);
}
},
"processing": true,
"columns": [
{ "data": "fieldA" },
{ "data": "fieldB" },
],
columnDefs: [
{
"targets": [0],
"visible": false,
"searchable": false
}
],
"order": [1, "desc"]
, "createdRow": function (row, data, index) {
$(row).click(function () {
$("#ajaxSpinner").removeClass("HideMeDisplay");
$("#TheHiddenRowNumber").val(data.FieldA)
$("form").submit();
});
}
});
i am using DataTables with Ajax data i want to put serial number for datatable
i tried below code
html
<div class="col-md-12">
<table class="table-striped table-bordered" id="salestbl">
<thead>
<tr><th>S.no</th><th>Invoice Number</th><th>Total Amount</th><th>Discoint Amount</th><th>Total Tax</th><th>Grand Total</th><th>Date</th></tr>
</thead>
<tbody>
</tbody>
</table>
</div>
ajax
$('#salestbl').DataTable( {
"fnRowCallback" : function(nRow, aData, iDisplayIndex){
$("td:first", nRow).html(iDisplayIndex +1);
return nRow;
},
destroy: true,
data: response,
columns: [
{ data: 'nRow' },
{ data: 'invoiceNum' },
{ data: 'totalAmt' },
{ data: 'disAmt' },
{ data: 'taxAmt' },
{ data: 'grandTotal' },
{ data: 'date' }
]
} );
when the dataTable targeted , it shows following alert
DataTables warning: table id=salestbl - Requested unknown parameter 'nRow' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4
whats wrong in the above code please help me out.
i found the answer we need to declare slno in beans class and add it to the json String and send to ajax
$('#salestbl').DataTable( {
"fnRowCallback" : function(nRow, aData, iDisplayIndex){
$("td:first", nRow).html(iDisplayIndex +1);
return nRow;
},
destroy: true,
data: response,
columns: [
{ data: 'nRow' },
{ data: 'invoiceNum' },
{ data: 'totalAmt' },
{ data: 'disAmt' },
{ data: 'taxAmt' },
{ data: 'grandTotal' },
{ data: 'date' }
]
} );
here it should not be { data: 'nRow' }, it should be the member variable of our class { data: 'slno' },
then data table will assign row number to the first td of every row
using
"fnRowCallback" : function(nRow, aData, iDisplayIndex){
$("td:first", nRow).html(iDisplayIndex +1);
return nRow;
},
above function , thank you to who ever replyed to my question.
The following code works fine for me:
$(document).ready(function () {
var t = $("#users").DataTable({
columnDefs: [{
"searchable": false,
"orderable": false,
"targets": 0
}],
order: [[1, 'asc']],
ajax: {
url: "/api/users",
dataSrc: ""
},
columns: [
{
data: "id"
},
{
data: "firstName"
},
{
data: "lastName"
},
{
data: "userName"
},
{
data: "id",
render: function (data) {
return "<a href='#'><i class='fa fa-eye js-view' data-id='" + data + "'></i></a> | <a href='#'><i class='fa fa-pencil js-edit' data-id='" + data + "'></i></a> | <a href='#'><i class='fa fa-trash js-delete' data-id='" + data + "'></i></a>";
}
}
],
Is there a way to use column indexes instead of names like this?:
$(document).ready(function () {
var t = $("#users").DataTable({
columnDefs: [{
"searchable": false,
"orderable": false,
"targets": 0
}],
order: [[1, 'asc']],
ajax: {
url: "/api/users",
dataSrc: ""
},
columns: [
{
data: 0
},
{
data: 1
},
{
data: 2
},
{
data: 3
},
{
data: 0,
render: function (data) {
return "<a href='#'><i class='fa fa-eye js-view' data-id='" + data + "'></i></a> | <a href='#'><i class='fa fa-pencil js-edit' data-id='" + data + "'></i></a> | <a href='#'><i class='fa fa-trash js-delete' data-id='" + data + "'></i></a>";
}
}
],
All I basically want to do is to be able to display the first 4 columns of a web API source or even choose which four columns to display by INDEX not by name. Is this possible?
Instead of converting the result of the AJAX call as was suggested, I implemented an "ugly hack" that proved effective. I was really surprised that my problem could not be solved conventionally by "index" so instead I created a pseudo-index that grabs the column names from data attributes in the table tag and fed it to numbered variables like this:
//Display first 4 columns of data
var f1 = $(".grid").attr("data-f1");
var f2 = $(".grid").attr("data-f2");
var f3 = $(".grid").attr("data-f3");
var f4 = $(".grid").attr("data-f4");
var f5 = $(".grid").attr("data-f5"); //this value is the same as f1
var t = $(".grid").DataTable({
columnDefs: [{
"searchable": false,
"orderable": false,
"targets": 0
}],
order: [[1, 'asc']],
ajax: {
url: "/api/users",
dataSrc: ""
},
columns: [
{
data: f1
},
{
data: f2
},
{
data: f3
},
{
data: f4
},
{
data: f5,
render: function (data) {
return "<a href='#'><i class='fa fa-eye js-view' data-id='" + data + "'></i></a> | <a href='#'><i class='fa fa-pencil js-edit' data-id='" + data + "'></i></a> | <a href='#'><i class='fa fa-trash js-delete' data-id='" + data + "'></i></a>";
}
}
],
This approach proved to be surprisingly flexible, as I could swap the display order of the column on the fly without changing the code. Still, I would have preferred the indexed approach, though.
I tried use the Kendo Grid and i found some problems.
The button action "edit" and "remove " do nothing when i click, but if i put the "create" command into the transport, the grid send lots of POSTS for the create URL command when i click in delete or click in edit > cancel (the update button do nothing too).
What I doing wrong?
My code:
<div id="grid"></div>
<script type="text/x-kendo-template" id="template">
<div class="toolbar">
<input type="number" min="0" id="item-id" maxlength="10" />
<input type="text" id="name" class="k-textbox" placeholder="..." />
<button style="width: 100px" id="btn-grid-filtrar" class="k-button" >Filter</button>
</div>
</script>
<script>
$(document).ready(function() {
var dataSource = new kendo.data.DataSource(
{
schema:
{
data: "data",
total: "total",
model:
{
id: "data",
fields:
{
id: { editable: false, nullable: false },
nome: { type: "string", validation: { required: true} },
ativo: { type: "boolean" }
}
}
},
transport:
{
read:
{
url: "page",
dataType: "json",
type: "POST",
data: additionalData
},
update: {
url: "update",
dataType: "jsonp"
},
destroy: {
url: "delete",
dataType: "jsonp"
}
/*,
create: {
url: "add",
dataType: "jsonp"
}
*/
},
pageSize: 5,
serverSorting: true,
serverPaging: true,
});
var grid = $("#grid").kendoGrid({
dataSource: dataSource,
sortable: true,
pageable: {
input: true,
numeric: false
},
batch: true,
columns: [
{ field: "id", title: "#", width: "60px" },
{ field: "nome", title: "Nome" },
{ field: "ativo", title: "Ativo", width: "60px", template: "#= ativo ? 'Sim' : 'Não' #" },
{ command: ["edit", "destroy"], title: "Ações", width: "200px" }
],
editable: "inline",
toolbar: kendo.template($("#template").html()),
});
kendo.bind($(".toolbar"));
$("#id").kendoNumericTextBox({
format: "##########",
placeholder: "..."
});
$("#btn-grid-filtrar").click(function() {
grid.data("kendoGrid").dataSource.read();
});
});
function additionalData() {
return {
filtro_id: $("#item-id").val(),
filtro_nome: $("#name").val()
};
}
</script>
First of all, I'm assuming that you server is serving a JSON with the following format:
{
"total": 2,
"data" : [
{
"data" : 23,
"id" : 1,
"ativo": true,
"nome" : "stock-1"
},
{
"data" : 34,
"id" : 2,
"ativo": false,
"nome" : "stock-2"
}
]
}
Correct?
So the first thing is changing the "data" on each row data to something not called data. It turns out that data is a kind-of reserved word in KendoUI commonly used in code structures as:
with (data) {
// Expanded code coming from a grid row data
}
Where this data is a variable referencing a row in your grid. So, in this context data is both the row itself and and a field in that row and then JavaScript cannot correctly solve it.
So you can define your schema as:
schema : {
data : "data",
total: "total",
model: {
id : "_data",
fields: {
id : { editable: false, nullable: false },
nome : { type: "string", validation: { required: true} },
ativo: { type: "boolean" }
}
}
},
NOTE: I've replace data by _data.
Transmitted data is:
{
"total": 2,
"data" : [
{
"_data" : 23,
"id" : 1,
"ativo": true,
"nome" : "stock-1"
},
{
"_data" : 34,
"id" : 2,
"ativo": false,
"nome" : "stock-2"
}
]
}
Just with this small change your Edit button will start working.
You are not supposed to define transport level for local datasources, if understand correctly your code, you are not posting anywhere - you are not binding any remote data, I can't see any url ? Follow this example http://demos.kendoui.com/web/datasource/index.html.