How to remove multiple header from kendo grid - javascript

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.

Related

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>

Kendo Grid Change dynamic columns title on databound

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

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

How to load extjs 4 grid data on form submission?

I am new to ExtJS.
I am developing a page which has a form at the top and a grid below. When user enters the search criteria in the form and enters Submit, grid has to be populated with data accordingly.
I have managed to get the JSON data from server to the client
console.log('response.responseText');
prints the data correctly, but unable to assign that to the grid.
Here is my code
Ext.define('colModel', {
extend: 'Ext.data.ColumnModel',
fields: [
'personId',
'country',
'idType',
'idValue'
]
});
// create the data store
var store = Ext.create('Ext.data.ArrayStore', {
model: 'colModel',
fields: [
{name: 'personId'},
{name: 'country'},
{name: 'idType'},
{name: 'idValue'}
],
proxy: {
type: 'ajax',
reader: {
type: 'json',
root: 'person'
}
},
autoLoad: false,
});
// create the Grid
var grid = Ext.create('Ext.grid.Panel', {
store: store,
stateful: true,
id: 'myGrid',
stateId: 'stateGrid',
columns: [
{
text : 'Person Id',
flex : 1,
sortable : false,
dataIndex: 'personId'
},
{
text : 'Country',
width : 75,
sortable : true,
dataIndex: 'country'
},
{
text : 'ID Type',
width : 75,
sortable : true,
dataIndex: 'idType'
},
{
text : 'Id Value',
width : 75,
sortable : true,
dataIndex: 'idValue'
},
],
height: 350,
title: 'Array Grid',
renderTo: 'bottom',
viewConfig: {
stripeRows: true,
ForceFit: true,
loadMask:false
}
});
and this function get invoked after form submission and response returned from server
displayGrid : function(response, opts) {
//Received response from the server
console.log('On Success');
responseData = Ext.decode(response.responseText);
console.log('response success ',responseData);
console.log(Ext.getCmp('myGrid').getStore());
grid.getStore().loadData('colModel',false);
}
I have managed to populate grid data on page load using the following code
var store = Ext.create('Ext.data.ArrayStore', {
model: 'colModel',
proxy: {
type: 'rest',
url : 'PersonSearch',
reader: {
type: 'json',
root: 'person'
}
},
autoLoad: true
});
but failed to load grid data on form submission.
Please help. Thanks in advance.
PS: I am using ExtJS 4.2
Update
This is the JSON update, I am getting from the server(caught using Firefox Browser Console)
"{"person":[{"personId":"1","country":"country 1","idType":"idType 1","idValue":"idValue 1"},{"personId":"2","country":"country 2","idType":"idType 2","idValue":"idValue 2"},{"personId":"3","country":"country 3","idType":"idType 3","idValue":"idValue 3"},{"personId":"4","country":"country 4","idType":"idType 4","idValue":"idValue 4"},{"personId":"5","country":"country 5","idType":"idType 5","idValue":"idValue 5"}]}
"
You aren't actually loading the data. Your data is stored in responseData, so your loadData call should load that data into the store. So, your loadData call should be as follows:
grid.getStore().loadData(responseData);
Note that this assumes that your responseData is in the correct format for the store you are loading it into. (Also note that the second parameter is false by default, so it isn't necessary to include it in this case)
Used forgivenson comment and set autoLoad: true
and
Updated the displayGrid method as below
displayGrid : function(response, opts) {
//Received response from the server
console.log('On Success');
responseData = Ext.decode(response.responseText,false);
console.log(response.responseText);
grid.getStore().loadData(responseData.person);
}
and the grid gets populated correctly.

Lazy Load with Scrollable {Virtual:true} not working in Kendo UI Grid

I am facing an issue to implement lazy loading in kendo ui grid.
I added scrollable virtual property and backend server side code to handle it but issues is after adding scrollable property I am unable to see scroll bar in my Grid.
Even the selected rows (20 page size) disappears off the bottom of the grid into the hidden overflow area.
Here is my code.
var managecustomerGrid = $("#customerGrid").kendoGrid({
dataSource: {
schema: {
data: "results",
total : "totalRecords",
model: {
id: "SRNUMBER",
fields: {
SRNUMBER : {type: 'number'},
CUSTOMERNAME : {type: 'string'},
DATEPAID : {type: 'string'}
}
}
},
serverPaging: true,
serverSorting: true,
serverFiltering: true,
pageSize: 20,
batch: false,
transport: {
read: {
type: "POST",
url: "/customer/customer.cfc",
dataType: "json",
error: function (xhr, error) {
alert('Error In Getting Customer Information.');
}
},
parameterMap: function(options, type) {
return {
ntPageNumber: options.page,
ntRowLimit: options.pageSize,
vcSortOrder: JSON.stringify(options.sort),
vcFilterCondition: JSON.stringify(options.filter)
}
}
}
},
toolbar: kendo.template($("#template").html()),
height: 600,
scrollable: {
virtual: true
},
filterable: {
operators: {
string: {
contains: "Contains",
startswith: "Starts with",
endswith: "Ends with",
eq: "Is equal to",
doesnotcontain: "Doesn't contain"
}
}
},
sortable: true,
columns: [
{ field: "SRNUMBER", title: "SR No.", width: "80px", template: "<span id='#=SRNUMBER#'>#=SRNUMBER#</span>"},
{ field: "CUSTOMERNAME", title: "Customer Name", width: "110px"},
{ field: "DATEPAID", title: "Date", width: "110px"},
{ command: ["edit","detail","cancel"], title: " ", title: "Actions", width: "130px", filterable: false, sortable: false}
]
});
Please let me know if any one find any issues. I am unable to get it.
The kendo grid does not really support Lazy Loading out of the box. It may be easier to instead just make a blank scroll-able grid (without paging), and then to populate the data with ajax calls. You can use $.merge() to append data to the data array with little to no impact on performance.
$.ajax({
url: '/getNextData',
data: { filter: 'foo', lastLoaded: $("#Grid").data("kendoGrid").dataSource.at($("#Grid").data("kendoGrid").dataSource.total()-1).ID },
dataType: "json",
success: function (newData) {
$("#Grid").data("kendoGrid").dataSource.data($.merge($("#Grid").data("kendoGrid").dataSource.data(), newData))
},
error: function (e) { console.log(e); }
});
In this ajax example I load the next data based on the current last item in the grid and a filter. I just append the response to the currently loaded data.
I faced the same issue, my problem was the controller code. Here I am posting my controller hoping it would help someone someday
public JsonResult GetJson(int? projectid,int skip, int take, int pageSize, int page)
{
using (sqlCon)
{
var myData = sqlCon.Query<Device>("Select * from workbook.dbo.TargetList", new { projectid = projectid });
var data = myData .Skip(skip).Take(pageSize).ToList();
var total = myData .Count();
var json = new { data = myData };
var jsonResult = Json(new {data= data, total= total}, JsonRequestBehavior.AllowGet);
jsonResult.MaxJsonLength = int.MaxValue;
return jsonResult;
}
}

Categories

Resources