Kendo Grid Change dynamic columns title on databound - javascript

I have a kendo Grid with no columns definition because grid's fields are dynamics and I don't have any chance to know the fields before databound event.
Example:
var dataSource = new kendo.data.DataSource({
type: "aspnetmvc-ajax",
transport: {
read: {
url: appPath + "Controller/GetGridData",
dataType: "json",
type: "POST",
data: {
dataSourceID: dataSourceId
}
},
},
schema: { data: "data", total: "total"},
pageSize: 10,
serverSorting: true,
serverPaging: true,
serverFiltering: true,
});
$("#grid").kendoGrid({
dataSource: dataSource,
filterable: {
extra: false
},
dataBound: function (data) {
},
pageable: {
pageSizes: true,
pageSizes: [10, 20, 50, 100]
}
)}
Is there a way to modify columns headers dynamically on databound event or after data are loaded but before showing it to users?

I achieved "dynamic" column headers (after many infuriating troubleshooting messages back and forth by Telerik) by requesting the data prior to initialising the grid via an AJAX call then determining the column names based on the data.
$.ajax({
type: "POST",
url: "/Controller/GetGridData",
// *Important* stringify the server-bound object
data: JSON.stringify(dataSourceId),
dataType: "json",
contentType: "application/json",
async: true,
success: function(response) {
// response contains data required for grid datasource
ConstructGrid(response);
}
});
function ConstructGrid(gridData) {
var dataSource = new kendo.data.DataSource({
... attributes
data: gridData,
... more attributes
});
var columnsArray = [];
if(gridData.attributeToCheck = "someValue") {
columnsArray.push({field: attributeEqualToSomeValue, title="attributeMatchingSomeValue"});
}
else {
columnsArray.push({field: attributeNotEqualToSomeValue, title="attributeNotMatchingSomeValue"});
}
.. continue to add more columns based on data then initialise grid
$("#grid").kendoGrid({
dataSource: dataSource,
filterable: {
extra: false
},
columns: columnsArray,
pageable: {
pageSizes: true,
pageSizes: [10, 20, 50, 100]
}
)};
}
Not exactly 100% dynamic but it will change the column names based on the values retrieved from the AJAX call and AFAIK (after chatting back and forth with Telerik), truly dynamic columns are not supported by the grid control.

Check this Jsbin
`https://output.jsbin.com/lesoxes/`
In this example i have used kendo's datasource.
you will get all column details in console.
Might Help You

Related

jquery Datatable manipulation causing the entire page to reload

I have a jQuery datatable that is initially populated using ajax call, and when i click anywhere on the table like pagination number or display length dropdown list, the whole page is reloaded indefinetely. Here is how i populate the datatable.
let table = $('#data-table').DataTable();
function populateTable(){
table = $('#data-table').DataTable({
destroy: true,
responsive: true,
serverSide: false,
autoWidth: false,
paging: true,
filter: true,
searching: true,
stateSave: true,
scrollX: true,
lengthMenu: [10, 25, 50, 75, 100],
language: {
"search": "Filtrer: "
},
ajax: {
url: '/Observer/GetActiveClientsByFloor',
type: 'POST',
data: {
FloorId: floorId,
Type: type
},
dataSrc: ''
},
columns: [
{
title: 'Zone',
data: 'LastKnownZone',
},
{
title: 'HiƩrarchie Map',
data: 'MapInfo.mapHierarchyString',
},
{
title: 'Addresse MAC',
data: 'macAddress',
},
{
title: 'SSID',
data: 'ssId',
},
],
createdRow: (row, data, dataIndex, cells) => {
const selectedRowProfileId = $('#selectedRowProfileId', window.parent.document).val();
if (selectedRowProfileId !== '') {
if (data['ProfileId'] === selectedRowProfileId) {
$(row).addClass('selectedCustom');
}
}
},
initComplete: function (settings, json)
{
const response = json;
//Show the respone on other part of the page
}
}).order([[1, 'asc']]).draw(false);
}
I would like to know what could be causing page re-load and also know how to make pagination works.
You don't need to call order([[1, 'asc']]).draw(false) after table initialization, just add
order: [[1, 'asc']]
to your table properties, like this
$(document).ready(function(){
let table = $('#data-table').DataTable({
order: [[1, 'asc']],
//Other properties
});
As you are not using server-side DataTables will make pagination automatically when you click pagination buttons, considering that all data has already been loaded in the first Ajax call, but when serverSide is set to true every time you change the pagination a new Ajax call will be made by datatables sending aditional parameters for pagination, ordering etc and you will need to change you backend query, filters and pagination logic based on that params.
Edit:
Also destroy: true is not needed in your case, as Documentation says:
"Destroy any existing table matching the selector and replace with the new options."
You are not re-creating or replacing your table, so you can just remove it

How to remove multiple header from kendo grid

I am creating a sample application in which I show data in kendo grid.
For this I get the page size data in kendo grid and then load it. when page change I load next data.
When my page change event call the grid is added in already exist grid. By this it shows multiple column header.
My sample is - http://jsfiddle.net/pporwal26/y6KdK/78/
var jsonData = JSON.parse("{\"Report\":\"type1\",\"FileList\":[{\"owner\":\"machine-174\\\\admin\",\"path\":\"C:\\\\workarea\\\\WinTest1lakhfileinKB\\\\WinTest\\\\nGYh\\\\SMv\\\\U1P8FLx\\\\vMbhdo\\\\TgFSW\\\\42Ioulj0w.txt\"},{\"owner\":\"machine-174admin\",\"path\":\"C:\\\\workarea\\\\bada_data\\\\Employee Database - Copy (7) - Copy.mdb\"}],\"Count\":100,\"total\":100,\"page\":4}");
function nextData(page){
jsonData = JSON.parse("{\"Report\":\"type1\",\"FileList\":[{\"owner\":\"machine-170\\\\admin\",\"path\":\"C:\\\\workarea\\\\WinTest1lakhfileinKB\\\\WinTest\\\\nGYh\\\\SMv\\\\U1P8FLx\"},{\"owner\":\"machine-170admin\",\"path\":\"C:\\\\workarea\"}],\"Count\":100,\"total\":100,\"page\":5}");
$("#grid").kendoGrid({ dataSource: {
serverPaging: true,
schema: {
data: "FileList",
total: "total"
},
data: jsonData
} })
}
createGrid(jsonData);
function createGrid(jsonData){
$("#grid").kendoGrid({
pageable: true,
scrollable: true,
pageable: {
pageSize: 2,
refresh: true,
change:function(e){
nextData(e.index);
}
},
dataSource: {
serverPaging: true,
schema: {
data: "FileList",
total: "total",
},
data: jsonData
}
});
}
How I remove multiple header when page change event call?
Try modifying your nextData function as below.
function nextData(page){
jsonData = JSON.parse("{\"Report\":\"type1\",\"FileList\":[{\"owner\":\"machine-170\\\\admin\",\"path\":\"C:\\\\workarea\\\\WinTest1lakhfileinKB\\\\WinTest\\\\nGYh\\\\SMv\\\\U1P8FLx\"},{\"owner\":\"machine-170admin\",\"path\":\"C:\\\\workarea\"}],\"Count\":100,\"total\":100,\"page\":5}");
var _dataSource = new kendo.data.DataSource({
schema: {
data: "FileList",
total: "total"
},
data: jsonData,
serverPaging : true,
pageSize : 2,
page : page
});
$("#grid").data("kendoGrid").setDataSource(_dataSource);
}
http://jsfiddle.net/y6KdK/79/
var grid = createGrid(jsonData);
create the instance of your grid.
var dataSource = new kendo.data.DataSource({
data: jsonData
});
grid.setDataSource(dataSource);
And set your newly created datasource into your nextData function. please see the above fiddle link.

Kendo Grid: populating with data from ajax

I'm trying to populate a kendo grid with data retrieved via ajax. Here is the ajax:
var model = #Html.Raw(Json.Serialize(Model));
$(document).ready(function () {
$.ajax({
url: "/Utilities/Report/Run",
data: JSON.stringify(model),
contentType: "application/json",
type: "POST",
success: function(result) {
var ds = new kendo.data.DataSource({
data: result
});
alert(result);
$("#grid").data("kendoGrid").setDataSource(ds);
},
error: function(result) {
options.error(result);
}
});
$("#grid").kendoGrid({
toolbar: ["excel", "pdf"],
excel: {
fileName: "test"
},
pdf: {
fileName: "test"
},
});
});
At the alert(result) this is what the data looks like:
[
{"TEST":"one"},
{"TEST":"two"},
{"TEST":"three"}
]
The ajax call appears to be working and the data looks good to me, but the kendo grid is not updating, it remains blank. I also do not get any error. I've tried placing the kendoGrid inside the ajax success function with the same result. I've tried using transport and read in the DataSource to retrieve the data but that kept giving me an error: n.slice is not a function. However, others seemed to think that was because there was no schema defined. Due to the kind of data I am retrieving, I cannot define this. The data retrieved from the server could have any column/field names, and any number of columns. It is not complex JSON however.
How do I get my grid to populate with this data?
I have created a new Datasource and mapped it to the existing one outside the success method.
Can you try this one below :
var newDataSource = new kendo.data.DataSource({
transport: {
read: {
url: "/Utilities/Report/Run",
dataType: "json",
data: JSON.stringify(model),
error: function (result) {
options.error(result);
}
}
}
});
var d1 = $("#grid").data("kendoGrid");
d1.dataSource.data([]);
d1.setDataSource(newDataSource );
make changes as per your necessity if I have missed any . Kendo data binding is always confusing :D
Kendo DataSource is very powerful. Ideally, you do not need to make a manual Ajax call. Instead, DataSource can Ajax request data from URL by itself, if Grid needs data.
https://jsfiddle.net/6gxqsrzu/
$(function() {
var dataSource = new kendo.data.DataSource({
type: "odata",
transport: {
read: "https://demos.telerik.com/kendo-ui/service/Northwind.svc/Orders"
},
schema: {
model: {
fields: {
OrderID: {
type: "number"
},
Freight: {
type: "number"
},
ShipName: {
type: "string"
},
OrderDate: {
type: "date"
},
ShipCity: {
type: "string"
}
}
}
},
serverPaging: true,
pageSize: 5,
serverSorting: true,
sort: {
field: 'OrderDate',
dir: 'asc'
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
sortable: true,
pageable: true,
columns: [{
field: "OrderID",
filterable: false
},
"Freight", {
field: "OrderDate",
title: "Order Date",
format: "{0:MM/dd/yyyy}"
}, {
field: "ShipName",
title: "Ship Name"
}, {
field: "ShipCity",
title: "Ship City"
}
]
});
});
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.2.621/styles/kendo.common-material.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.2.621/styles/kendo.material.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.2.621/styles/kendo.material.mobile.min.css" />
<script src="https://kendo.cdn.telerik.com/2017.2.621/js/jquery.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2017.2.621/js/kendo.all.min.js"></script>
<div id="grid"></div>

jsGrid won't render JSON data

I'm trying to use jsGrid in my MVC project as the client would like inline editing and filtering.
However, I cannot get it to load my JSON source into the table.
My js to load the table looks like so:
$("#jsGrid").jsGrid({
height: "50%",
width: "100%",
filtering: true,
inserting: true,
editing: true,
sorting: true,
paging: true,
autoload: true,
pageSize: 10,
pageButtonCount: 5,
deleteConfirm: "Do you really want to delete client?",
controller: {
loadData: function (filter) {
return $.ajax({
type: "GET",
url: "RICInstrumentCode/GetData",
data: filter,
dataType: "json"
});
},
insertItem: function (item) {
return $.ajax({
type: "CREATE",
url: "/api/RICInsrumentCodeTable",
data: item,
dataType: "json"
});
},
updateItem: function (item) {
return $.ajax({
type: "UPDATE",
url: "/api/RICInsrumentCodeTable/" + item.ID,
data: item,
dataType: "json"
});
},
deleteItem: $.noop
//deleteItem: function (item) {
// return $.ajax({
// type: "DELETE",
// url: "/api/data/" + item.ID,
// dataType: "json"
// });
//}
},
fields: [
{ name: "Code", type: "text", title: "RIC Instrument Code", width: 150 },
{ name: "Descr", type: "text", title:"RIC Instrument Code Description", width: 200 },
{ name: "RICInstrumentGroupId", type: "select", title: "RIC Instrument Group", items: countries, valueField: "Id", textField: "Name" },
{ name: "Active", type: "checkbox", title: "Is Active", sorting: true },
{ type: "control" }
]
});
});
The loadData is what I've been working on.
and the JSON the is returned from get data looks like so:
[{"Id":1,"Code":"test1","Descr":"first code test","RICInstrumentGroupId":2,"Active":true},{"Id":2,"Code":"APP","Descr":"Apples and bananas","RICInstrumentGroupId":4,"Active":true},{"Id":3,"Code":"1","Descr":"1","RICInstrumentGroupId":1,"Active":true},{"Id":4,"Code":"3","Descr":"3","RICInstrumentGroupId":3,"Active":false}]
So far I have confirmed that the ajax is firing, changed my array titles to match those of the call, and ensured the return is in valid JSON, what else can I do? Why isn't this working?
I was being stupid,
The bit that sets the table height was set to a 100% in a div that had no height, this was causing the table body to render with a height of 0px, changing the height property to auto fixed it because the data was there all along.
Thanks for the advice though!
I don't know if it is required, but when I look on demo examples (OData Service).
The grid loadData function looks bit different than yours.
loadData: function() {
var d = $.Deferred();
$.ajax({
url: "http://services.odata.org/V3/(S(3mnweai3qldmghnzfshavfok))/OData/OData.svc/Products",
dataType: "json"
}).done(function(response) {
d.resolve(response.value);
});
return d.promise();
}
is accept promise rather than ajax function. so that my be the problem
Demo here: http://js-grid.com/demos/

Kendo UI Datagrid - how to pass server pagination param to get new results after click on last item button?

i have Kendo datagrid which on onLoad method initialize datagrid and fetch some remote data in JSON from API.
I have for example 20 items to display which are correctly displayed. Problem is that i cannot make request for next values (button next is not active).
How i should to that correctly if i want to pass data to API via POST?
I think, that is it something with serverPaging params.
Thanks for any advice or example, hot to solve this issue.
Here is exe example of grid init:
$("#grid").kendoGrid({
selectable: "multiple cell",
navigatable: true,
dataSource: dataPacket,
filterable: true,
//page: 2, // unless the serverPaging option is set to true.
pageSize: 5,
serverFiltering: true,
serverSorting: true,
serverPaging: true,
groupable: true,
pageable: {
pageSizes: [5, 10, 50]
},
sortable: true,
scrollable: false,
reorderable: true,
resizable: true,
columnMenu: true,
height: 550,
toolbar: ["create", "save", "cancel"],
columns: ["id",
Read function:
$scope.initGrid = function () {
var requestParams = {
"token":"test",
"data":{
"test":"test"
}
};
var token = localStorage.getItem($rootScope.lsTokenNameSpace);
var dataPacket;
dataPacket = new kendo.data.DataSource({
transport: {
// READ FUNCTION
read: function (options) {
console.log("List");
// call the service
ApiService.doHttpRequest("POST", $rootScope.apiBaseUrl + "user/list", requestParams)
.success(function (data, status, headers, config) {
// successful data retrieval
console.log("request success");
console.log("state: "+status);
console.log(data);
options.success(data);
// do something with data
})
.error(function (data, status, headers, config) {
// do some stuff
console.log("request processing error");
console.log(data);
});
},
I will post Kendo UI API reference for Kendo UI dataSource here. Take a look at it.
http://docs.telerik.com/kendo-ui/api/framework/datasource#configuration-serverPaging
You need pass needed parameters to fetch more data after first set.
myDataSource = new kendo.data.DataSource({
transport: {
read: {
url: "/api/search",
type: "POST",
dataType: "json",
contentType: "application/json",
parameterMap: function( data, type ) {
return JSON.stringify( { query: $("#searchBox").val(), start: data.page, sort: data.sort, pageSize: data.pageSize } );
}
}
},
serverPaging: true,
serverSorting: true,
pageSize: 100,
schema: {
data: "data",
total: "total"
}
});

Categories

Resources