I have this problem when trying to pass a string parameter from DataTable with Ajax to an ASP.NET MVC controller: the parameter is not being sent.
I tried many forms of "data:" options. Please help me, I think I'm missing something important.
When (as a test) I initialize the parameter at the beginning of the controller with ttt="CO" everything goes fine!
$('#tblVacation').DataTable({
"ajax": {
"url": '/Vacation/LoadData2',
"contentType": "application/json;charset=utf-8",
"type": 'GET',
"dataType": 'JSON',
"data" : ' { ttt: "CO" }'
"dataSrc": "",
},
"columns": [
{ "data": "vacationId", width: "5%" },
{ "data": "operatorId", width: "3%" },
{ "data": "operator", width: "10%" },
{ "data": "type", width: "3%" },
]
});
And the controller is:
[HttpGet]
public ActionResult LoadData2(string ttt)
// ttt="CO";
{
List<Vacation> data = null;
try
{
data = DB.Vacations.Include(x => x.Operator).ToList();
var result = data.Select(x => new Vacation_VM
{
VacationId = x.VacationId,
OperatorId = x.OperatorId,
Vacation_doc = x.Vacation_doc,
Operator = x.Operator.Name,
Type = x.Type,
}).Where(m => m.Type == ttt);
return new JsonResult(result);
}
catch (Exception ex)
{
ViewBag.Message = ex.Message;
}
return new JsonResult(null);
}
I also tried with
var entity = {
ttt: "CO"
}
var dataToSend = JSON.stringify(entity);
and
"data": function () {
return dataToSend;
},
but it's still not working. I will need in the future to pass multiple parameters.
Thanks a lot, I will appreciate any advice.
Replace the ajax call part with the followings:
"ajax": {
type: 'GET',
url: '/Vacation/LoadData2',
data: { ttt: "CO" },
dataType: 'JSON',
async: true,
cache: false,
},
Related
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
So, I'm trying to make a readyonly grid with kendo that shows data, but whatever I do, the data does not get shown.
The grid looks like this
And here's the code:
$("#Materials")
.kendoGrid({
dataSource: {
data: [],
schema: {
model: {
id: "ID",
fields: {
ID: { type: "number", editable: false },
Code: { type: "string", editable: false },
Name: { type: "string", editable: false },
ExtDeviceCode: { type: "string", editable: false , nullable: true },
BaseUomLOVString: { type: "string", editable: false }
}
}
},
pageSize: 20
},
filterable: {
extra: true
},
pageable: true,
columns: [
{ field: "Code", title:"Code"},
{ field: "Name", title: "Name"},
{ field: "ExtDeviceCode", title:"External device code"},
{ field: "BaseUomLOVString", title: "UnitsOfMeasure" }
],
editable: false
});
This makes an empty grid with no data, which I later on fill with an Ajax call. As you can see from above picture, the grid contains the data but does not display it. The data inside the dataSource looks like this. or as Json:
[{
"ID": 21150,
"Code": "3",
"ExtDeviceCode": null,
"Name": "Avio benzin",
"BaseUomLOVString": "Kilogram"
}, {
"ID": 21400,
"Code": "5003",
"ExtDeviceCode": null,
"Name": "Bencin 95",
"BaseUomLOVString": "Litre"
}]
EDIT 1: I'm filling the data with an Ajax call like this:
$.ajax({
url: '#SimpleUrlHelper.UrlObjectToRoot(Url)/FuelPointMaterialTankMask/LookupMaterials',
data: {
//Send list of IDs
'materialIDs': materialList
},
type: "POST",
success: function (response) {
var tmp = [];
if (typeof response !== "undefined" &&
response !== null) {
response.forEach(function(item) {
tmp.push(item);
});
}
grid = $("#Materials").data("kendoGrid");
originalMaterialDataSource = grid.dataSource;
originalMaterialDataSource.data(tmp);
originalMaterialDataSource._destroyed = [];
originalMaterialDataSource.pageSize(pageSize);
originalMaterialDataSource.page(1);
originalMaterialDataSource._total = tmp.length;
grid.pager.refresh();
}
});
You can set your data in your dataSource after your ajax call.
var dataArray = [{
"ID": 21150,
"Code": "3",
"ExtDeviceCode": null,
"Name": "Avio benzin",
"BaseUomLOVString": "Kilogram"
}, {
"ID": 21400,
"Code": "5003",
"ExtDeviceCode": null,
"Name": "Bencin 95",
"BaseUomLOVString": "Litre"
}];
Use .data() to set:
$("#Materials").data('kendoGrid').dataSource.data(dataArray );
Okay so after days of trying to figure out what was wrong I finally found the answer.
Somewhere along the lines I had:
var grids = $('.k-grid');
for (var i = 0; i < grids.length; i++) {
....
grid.dataSource.filter().filters[0] = {
logic: "or",
filters: filters
}
....
So basically I was putting filters on all grids without excluding this one, which was just a bug from my part.
Here i'm trying Fuelux Tree used in Ace admin Template. I have used the same code they have used.
The script code used in ace admin template:
jQuery(function($) {
var tree_data = {};
var sampleData = initiateDemoData(tree_data); //see below
$('#tree1')
.ace_tree({
dataSource: sampleData['dataSource1'],
multiSelect: true,
cacheItems: true,
'open-icon': 'ace-icon tree-minus',
'close-icon': 'ace-icon tree-plus',
'selectable': true,
'selected-icon': 'ace-icon fa fa-check',
'unselected-icon': 'ace-icon fa fa-times',
loadingHTML: '<div class="tree-loading"><i class="ace-icon fa fa-refresh fa-spin blue"></i></div>'
});
function initiateDemoData(tree_data) {
tree_data = {
"2C27D744B956": {
"text": "2C27D744B956",
"children": {
"001B179F4400": {
"text": "9991100003333",
"type": "item"
},
"9991100003333": {
"text": "9991100003333",
"type": "item"
},
"2c27d744b956": {
"text": "9991100003333",
"type": "item"
},
"002170615A04": {
"text": "9991100003333",
"type": "item"
}
},
"type": "folder"
}
};
var dataSource1 = function(options, callback) {
var $data = null
if (!("text" in options) && !("type" in options)) {
$data = tree_data; //the root tree
callback({
data: $data
});
return;
} else if ("type" in options && options.type == "folder") {
if ("children" in options)
$data = options.children || {};
else
$data = {} //no data
}
if ($data != null) //this setTimeout is only for mimicking some random delay
setTimeout(function() {
callback({
data: $data
});
}, parseInt(Math.random() * 500) + 200);
//we have used static data here
//but you can retrieve your data dynamically from a server using ajax call
//checkout examples/treeview.html and examples/treeview.js for more info
}
return {
'dataSource1': dataSource1
}
}
});
Then on a button click i'm trying to refresh the tree, with new data from ajax Get request, But when i tried, an error comes in browser such as "Uncaught TypeError: Cannot read property 'apply' of undefined ".
Following is my ajax code:
$.ajax({
type : "GET",
url : "getDevices.htm?did=" + dID,
success : function(data) {
tree_data = data; //tree_data is the data used for the treeview
$('#tree1').tree('reload');
},
error : function(data) {
console.log("failure" + data);
}
});
Please suggest a method to resolve this issue.
Thanks in advance.
My grid won't call my parameterized DataSourceResult methods. It just calls the parameterless one. I've studied this article till my eyes are falling out. What am I missing?
From my javascript controller:
$("#grid").kendoGrid({
dataSource: {
transport: {
read: function (options) {
userService.getGridUserList($.extend(options.data))
.success(function (result) { options.success(result); })
.error(function (result) { options.error(result); });
},
parameterMap: function(options, type) {
return kendo.stringify(options);
}
},
requestStart: function (e) {
},
requestEnd: function (e) {
},
schema: {
data: "data",
total: "total"
},
pageSize: 25,
serverPaging: true,
serverSorting: true,
serverFiltering: true
},
height: 600,
filterable: true,
sortable: true,
pageable: true,
columns: [
{ field: "firstName", title: "First Name" },
{ field: "lastName", title: "Last Name" },
{ field: "email", title: "email" }
]
});
From my C# WebAPI:
//**doesn't get called**
public DataSourceResult GetGridUserList(GetUserGridListInput input)
{
var q = repository.GetAll().OrderBy(t => t.Id);
return q.ToDataSourceResult(input.Take, input.Skip. input.Sort, input.Filter);
}
//**doesn't get called**
public DataSourceResult GetGridUserList(int take, int skip, IEnumerable<Sort> sort, Filter filter)
{
var q = repository.GetAll().OrderBy(t => t.Id);
return q.ToDataSourceResult(take, skip, sort, filter);
}
//**gets called every time**
public DataSourceResult GetGridUserList()
{
var q = repository.GetAll().OrderBy(t => t.Id);
return q.ToDataSourceResult(500, 0, null, null);
}
Turns out I was clobbering the grid parameters in my service call. What I needed to fix it, is to add {} as the first parameter:
userService.getGridUserList({}, $.extend(options.data))
The example uses a POST request, perhaps the grid requires that.
"I'm using a POST since MVC blocks unsecured GETS by default. That's
good since we're going to be needing a POST request structure coming
up shortly."
After almost struggling for a week I have been able to make DataTable + JEditable + AutoComplete(BAssistance) with server side processing using Json to work.
I thought it would be useful to somebody out there.
$(document).ready(function() {
$('#example tbody td').editable(
function(value, settings) {
processEventForTable(this, value);
return(value);
},
"height": "20px"
});
oTableexample = $('#example').dataTable({
"bInfo": true,
"bProcessing" : true,
"bServerSide" : true,
"sAjaxSource" : "GetPaginationData.aspx",
"sPaginationType": "full_numbers",
"bPaginate" : true,
"fnServerData": function ( sSource, aoData, fnCallback ) {
var data = {"name" : "kObjectId",
"value" : definitionId};
aoData.push(data);
data = { "name" : "ObjectName", "value" : "example" };
aoData.push(data);
data = { "name" : "InstanceId", "value" : instanceId };
aoData.push(data);
data = { "name" : "IsNewRequest", "value" : IsNewRowAdded};
IsNewRowAdded = 0;
aoData.push(data);
debugger;
$.ajax( {
"dataType": 'json',
"type": "Get",
"url": sSource,
"data": aoData,
"success": fnCallback
});
},
"fnDrawCallback" : function() {
debugger;
SetDataTableIDAndAttachJEditable("example");
$('#example tbody td').editable( function(value, settings)
{
var aPos = oTableexample.fnGetPosition( this );
processEventForTableNew(aPos[0], aPos[1], value, "example");
return(value);
}
);
}
});
$.editable.addInputType('autocomplete', {
element : $.editable.types.text.element,
plugin : function(settings, original) {
$('input', this).autocomplete(settings.autocomplete.url, {
dataType:'json',
parse : function(data) {
return $.map(data, function(item) {
return {
data : item,
value : item.Key,
result: item.value
}
})
},
formatItem: function(row, i, n) {
return row.value;
},
mustMatch: false,
focus: function(event, ui) {
$('#example tbody td[title]').val(ui.item.label);
return false;
}
});
}
});
$("#example tbody td > span[title]").editable(
function(value,settings){
return value;
},
{
type : "autocomplete",
tooltip : "Click to edit...",
autocomplete : {
url : "autocompleteeg.aspx"
}
}
);
});
This code works perfectly fine.
DataTables use Server Side Processing. And I am submitting the changes to JEditable to javascript function. From there on Submit I am submitting the entire change array to server.
This code has become too long can anybody help me refactor it.
If there is any better way to accomplish the same thing then I am waiting for it. :)
Yeah cool Dude !
Just a small syntax error in your code.
} , { // opening bracket missing
"height": "20px"
}
Thanks a lot