Ajax DataTable initialization and Post - ajax

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 });
}

Related

How to Edit a row in Datatable .net core

I try to update a row in my datatable with .net core. Datatable show data and have a new/delete button that works. But when I try to edit a row, I can't get it to work.
Here is mi index.cshtml. Thanks
"ajax": {
"url": "../LoadIntervaloTrabajo",
"type": "POST",
"data": { "codigo": #Model.codigo},
"datatype": "json"
},
"columns": [
{ "data": "horario", "autowidth": true },
{ "data": "codigo", "autowidth": true },
{ "data": "descripcion", "autowidth": true },
{ "data": "horainicio", "autowidth": true },
{ "data": "duracion", "autowidth": true },
{ "data": "cortentrada", "autowidth": true },
{ "data": "cortintermedia", "autowidth": true },
{ "data": "cortsalida", "autowidth": true },
{ "render": function (data, type, row) {
return "<a href='#' class='btn btn-info' onclick=EditData('" + row.codigo + "'); >Editar</a>";
}
},
function EditData(codigo) {
var table = $("#customerDatatable").DataTable();
var r = table.rows(".selected").nodes()[0];
if ($(table.buttons(".editButton")[0].node).find("span").text() == "Cancel") {
$(r).children("td").each(function (i, it) {
if (i > 0) {
var od = table.cells(it).data()[0];
$(it).html(od);
}
});
setButtons('cancel');
} else {
$(r).children("td").each(function (i, it) {
if (i > 0) {
var h = $("<input type='text'>");
h.val(it.innerText);
$(it).html(h);
}
});
setButtons('edit');
}
I try to update a row in my datatable with .net core.
To implement updating row functionality, you can refer to the following code snippet.
Render two buttons for updating row within the last column
"columns": [
{
"data": "horario", "autowidth": true
},
{ "data": "codigo", "autowidth": true },
{ "data": "descripcion", "autowidth": true },
{ "data": "horainicio", "autowidth": true },
{ "data": "duracion", "autowidth": true },
{ "data": "cortentrada", "autowidth": true },
{ "data": "cortintermedia", "autowidth": true },
{ "data": "cortsalida", "autowidth": true },
{
"render": function (data, type, row) { return "<a href='#' class='btn btn-info' onclick = EditData(this); >Editar</a><a href='#' class='btn btn-info btn-hidden' onclick = UpdateData(this); >Updatear</a>"; }
}
]
JS function
function EditData(btnedit) {
//find current row
var $row = $(btnedit).parent().parent();
var $tds = $row.find("td").not(':nth-child(2)').not(':last');
$.each($tds, function (i, el) {
var txt = $(this).text();
$(this).html("").append("<input type='text' value=\"" + txt + "\">");
});
$(btnedit).siblings("a").removeClass("btn-hidden");
$(btnedit).addClass("btn-hidden");
}
function UpdateData(btnupdate) {
var $row = $(btnupdate).parent().parent();
var horario = $row.find("td:nth-child(1)").find("input").val();
var codigo = $row.find("td:nth-child(2)").text();
var descripcion = $row.find("td:nth-child(3)").find("input").val();
var horainicio = $row.find("td:nth-child(4)").find("input").val();
var duracion = $row.find("td:nth-child(5)").find("input").val();
var cortentrada = $row.find("td:nth-child(6)").find("input").val();
var cortintermedia = $row.find("td:nth-child(7)").find("input").val();
var cortsalida = $row.find("td:nth-child(8)").find("input").val();
var data_for_update = { "horario": horario, "codigo": codigo, "descripcion": descripcion, "horainicio": horainicio, "duracion": duracion, "cortentrada": cortentrada, "cortintermedia": cortintermedia, "cortsalida": cortsalida };
//console.log(data_for_update);
//make request to update data
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: "/{controller_name_here}/Update",
data: JSON.stringify(data_for_update),
success: function (json) {
console.log(json);
var $tds = $row.find("td").not(':nth-child(2)').not(':last');
$.each($tds, function (i, el) {
var txt = $(this).find("input").val()
$(this).html(txt);
});
$(btnupdate).siblings("a").removeClass("btn-hidden");
$(btnupdate).addClass("btn-hidden");
},
//...
});
}
CSS style
.btn-hidden{
display:none;
}
Test Result

Ajax datatable with pagination and lazy load

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();
});
}
});

My datatable is not working.What am I missing?

This is just a simple datatable that gets data from an Web api. I am
new to datatables and all I get in the ouput is that "No data is
available" I have tried every script part and the cdn from the
datatable website but nothing works
`<head>
<title>DataTable</title>
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css"/>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(
function () {
jQuery('#tblEmployee').DataTable(
{
ajax: {
"url": "http://localhost:57507/api/Employee/Get",
"dataSrc": ""
}
,
columns : [
{ data: 'Employee_Id' },
{ data: 'Project_Id' },
{ data: 'Grade_Id' },
{ data: 'Site_Id' },
{ data: 'Location_Id' },
{ data: 'StartDate' },
{ data: 'EndDate' },
{ data: 'BillRate' },
{ data: 'Role' },
]
}
);
console.log('End');
});
</script>'
</head>
This is the output window

DataTables Warning: Requested unknown parameter 'pCodigo' for row 0

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();
}
})

How do I pass parameters to javascript in a kendo grid column template?

I have a kendo grid with a column template. I try to pass a value from the current row as a parameter for my javascript function. My code:
{
field: "CrmTaskId",
title: "Crm ",
template: '<a href="javascript:hrefTest(#=CrmTaskId#);" ># if( CrmTaskId==null) {#<span><span># } else {#<span>#: CrmTaskId#<span>#} #</a>'
}
hrefTest is javascript function with one param. But it's not working. Any ideas?
It can be done like this
.ClientTemplate("<a href='javascript: void(0);'
onclick=\"return YourJSFunction('#= OpportunityUrl #');\">#= OpportunityName #</a>")
This is part of the column definition, so what it is saying is...Make the OpportunityName
clickable and pass in the OpportunityUrl. #= Field # is the syntax for pulling values off of the Model.
I have tried with your code but not able to reproduce this issue. Please create new HTML/CSHTML page and check it.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<link href="http://cdn.kendostatic.com/2014.1.318/styles/kendo.common.min.css" rel="stylesheet" />
<link href="http://cdn.kendostatic.com/2014.1.318/styles/kendo.default.min.css" rel="stylesheet" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://cdn.kendostatic.com/2014.1.318/js/kendo.all.min.js"></script>
</head>
<body>
<div id="grid"></div>
<script>
var movies = [
{ "CrmTaskId": 1, "rating": 9.2, "year": 1994, "title": "The Shawshank Redemption"},
{ "CrmTaskId": 2, "rating": 9.2, "year": 1972, "title": "The Godfather"},
{ "CrmTaskId": null, "rating": 9, "year": 1974, "title": "The Godfather: Part II" },
{ "CrmTaskId": '', "rating": 9.9, "year": 1874, "title": "The Godmother: Part III" }
];
function hrefTest(CrmTaskId)
{
alert("CrmTaskId is: " + CrmTaskId);
}
$(document).ready(function () {
$("#grid").kendoGrid({
dataSource: {
data: movies,
pageSize: 10
},
groupable: true,
sortable: true,
pageable: {
refresh: true,
pageSizes: true
},
columns: [{
field: "CrmTaskId",
title: "Crm"
}, {
field: "title",
title: "title"
},
{
template: '<a href="javascript:hrefTest(#=CrmTaskId#);" ># if( CrmTaskId==null) {#<span><span># } else {#<span>#: CrmTaskId#<span>#} #</a>'
}
]
});
});
</script>
</body>
</html>
Please try with the below code snippet.
Use this :
{
field: "Field",
editable: true,
title: "Title",
template: showRelatedLink,
allownull: true,
width: 100
}
and then in your function :
function showRelatedLink(container, options)
{
var yourVariable = container.YourField;
}
You can pass a field to a function like this too:
Grid:
columns: [
{ field: "ProductTypeID", title: "Type", template: "#=product_type_to_name(ProductTypeID)#" },
]
Function:
function product_type_to_name(product_type_id) {
console.log(product_type_id);
var name = "";
// convert ID to name
return name;
}
I have tried this
{
field: "DisplayChangedFrom",
title: "From",
template:"#=generateTemplate(DisplayChangedFrom)#
},
Then the function
function generateTemplate(items) {
var html = "<ul>";
if (items !== null && items.length > 0) {
for (var x = 0; x < items.length; x++) {
html += "<li>";
html += items[x];
html += "</li>";
}
}
html += "</ul>";
return html;
};

Resources