I need help about a kendo grid,
I call a webservice to fill a datasource of the grid. It seems to work fine, but the data are not displayed in the grid.
The webservice call returns 7 records, and in the grid there are 7 rows, but they are empty.
this is the code:
var mime_charset = "application/json; charset=utf-8";
var serverSelectReturnsJSONString = true;
var model_definition = {
id: "ID",
fields: {
customer_id: { type: "number" },
name_customer: { type: "string" },
address_customer: { type: "string" }
}
}
$(document).ready(function () {
var ds = createJSONDataSource();
$("#grid").kendoGrid({
selectable: true,
theme: "metro",
dataSource: ds,
scrollable: true,
pageable: true,
// height: 300,
toolbar: ["save", "cancel"],
columns: ["ID", "Nome", "Indirizzo"],
editable: true
});
ds.read();
});
and this is the function for filling the datasource:
function createJSONDataSource() {
var dataSource = new kendo.data.DataSource({
severFiltering: true,
serverPaging: true,
PageSize: 15,
//batch: true,
transport: {
autoSync: true,
read: {
type: "POST",
url: "WebServices/GetDataTest.asmx/getCustList",
dataType: "json",
contentType: mime_charset
}
},
schema: {
data: function (data) {
if (data) {
if (serverSelectReturnsJSONString)
return $.parseJSON(data.d);
else
return data.d;
}
},
total: function (result) {
if (!result) return 0;
var xxx = result.d;
if (xxx == null) {
return result.length || 0;
}
if (result.d) {
if (serverSelectReturnsJSONString) {
var data = $.parseJSON(result.d);
return data.length || 0;
}
else {
return result.d.TotalRecords || result.d.length || result.length || 0;
}
}
},
model: model_definition
}
});
dataSource.options.schema.parse = function (dataJ) {
var data;
data = $.parseJSON(dataJ.d);
if (data) {
$.each(data, function (i, val) {
$.each(model_definition.fields, function (j, col) {
if (col.type == "date" || col.type == "datetime") {
val[j] = toDate(val[j]);
}
})
});
var ret = { d: JSON.stringify(data) };
return ret;
}
}
dataSource.reader.parse = dataSource.options.schema.parse;
return dataSource;
}
Your columns definition is not correct, it is an array but of objects (not strings). Check documentation here. If should be something like:
columns: [
{ field: "ID" },
{ field: "Nome" },
{ field: " "Indirizzo" }
],
Related
I use kendoDropDownList and have the following code:
<div id="memberNotInit-grid"></div>
<script>
$(document).ready(function () {
$("#memberNotInit-grid").kendoGrid({
dataSource: {
type: "json",
transport: {
read: {
url: "#Html.Raw(Url.Action("MemberNotInitList", "RandomPoolInit"))",
type: "POST",
dataType: "json",
data: function() {
var data = {
};
addAntiForgeryToken(data);
return data;
}
}
},
schema: {
data: "Data",
total: "Total",
errors: "Errors"
},
error: function(e) {
display_kendoui_grid_error(e);
// Cancel the changes
this.cancelChanges();
},
pageSize: #(Model.PageSize),
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
pageable: {
refresh: true,
pageSizes: [#(Model.AvailablePageSizes)],
#await Html.PartialAsync("_GridPagerMessages")
},
editable: {
confirmation: "#T("Common.DeleteConfirmation")",
mode: "inline"
},
scrollable: false,
columns: [
{
field: "FirstName",
title: "#T("PoolMemberList.Fields.FirstName")",
width: 150
},
{
field: "LastName",
title: "#T("PoolMemberList.Fields.LastName")",
width: 150
},
{
field: "Status",
template: columnTemplateFunction
},
{
field: "Reason",
width: 150,
template: "<input data-bind='value:Reason' class='reasonTemplate' />",
//hidden: true
}
],
dataBound: function (e) {
var grid = e.sender;
var items = e.sender.items();
items.each(function (e) {
var dataItem = grid.dataItem(this);
var ddt = $(this).find('.dropDownTemplate');
$(ddt).kendoDropDownList({
value: dataItem.value,
dataSource: ddlDataSource,
dataTextField: "displayValue",
dataValueField: "Status",
change: onDDLChange
});
var reason = $(this).find('.reasonTemplate');
$(reason).keydown(reasonChange);
reason.hide();
});
}
});
var ddlDataSource = [
{
Status: #((int)DriverRandomPoolStatus.Enrollment),
displayValue: "Enrollment"
},
{
Status: #((int)DriverRandomPoolStatus.Active),
displayValue: "Active"
},
{
Status: #((int)DriverRandomPoolStatus.Excused),
displayValue: "Excused"
}
];
function columnTemplateFunction(dataItem) {
var input = '<input class="dropDownTemplate"/>'
return input
};
function onDDLChange(e) {
var element = e.sender.element;
var row = element.closest("tr");
var grid = $("#memberNotInit-grid").data("kendoGrid");
var dataItem = grid.dataItem(row);
dataItem.set("Status", e.sender.value());
//alert(e.sender.value());
if (dataItem.Status == #((int)DriverRandomPoolStatus.Active)) {
$.ajax({
method: "POST",
url: "#Html.Raw(Url.Action("ChangeMemberStatus", "RandomPoolInit"))",
data: { id: dataItem.Id, status: dataItem.Status }
}).done(function () {
grid.tbody.find("tr[data-uid=" + dataItem.uid + "]").hide();
grid.pager.refresh();
});
}
if (dataItem.Status == #((int)DriverRandomPoolStatus.Excused)) {
grid.tbody.find("tr[data-uid=" + dataItem.uid + "]").find('.reasonTemplate').show();
var ddl = grid.tbody.find("tr[data-uid=" + dataItem.uid + "]").find('.dropDownTemplate');
//ddl.value(dataItem.Status);
}
};
function reasonChange(event) {
if (event.keyCode === 13) {
var element = event.target;
var row = element.closest("tr");
var grid = $("#memberNotInit-grid").data("kendoGrid");
var dataItem = grid.dataItem(row);
var r = grid.tbody.find("tr[data-uid=" + dataItem.uid + "]").find('.reasonTemplate').val();
$.ajax({
method: "POST",
url: "#Html.Raw(Url.Action("ChangeMemberStatus", "RandomPoolInit"))",
data: { id: dataItem.Id, status: dataItem.Status, reason: r }
}).done(function () {
grid.tbody.find("tr[data-uid=" + dataItem.uid + "]").hide();
grid.pager.refresh();
});
}
}
});
</script>
but when we select "Exclused" from dropdownlist value of dropdownlist is dumped to Enrollment (first value from dropdownlist). Why so and how to fix it?
I fixed it the following way:
$(ddt).kendoDropDownList({
value: dataItem.Status,
.....
});
not:
value: dataItem.value,
Requirement How to excel export hidden fields using kendoui grid
By using kendo editor i have implemented grid and i want to export hidden field using Excel export in kendo ui Grid Here I want to export Id field in Excel which is hidden here
My main moto is to export the hidden columns using excel export
<div id='grid-container'>
<div id='student-details-grid'
data-role='grid'
data-groupable='true'
data-sortable='true'
data-toolbar=['excel']
data-excel="{fileName: 'StudentDetails.xlsx', proxyURL: '/save', filterable: true, allPages: true}"
data-height='450px'
data-pageable="[
{'refresh':'true' },
{ 'pageSizes':'true'},
{'buttonCount':'5'}
]"
data-bind='source:gridDataSource'
data-columns="[{'field':'Id','title':'Id'},{'field':'Name','title':'Name'},{'field':'FatherName','title':'FatherName'},{'field':'Email','title':'Email'},{'field':'Address','title':'Address'},{'field':'ContactNo','title':'ContactNo'}]"
style="height: 550px">
</div>
</div>
<script type="text/javascript">
var viewModel = '';
$(document).ready(function (e) {
viewModel = kendo.observable({
gridDataSource: new kendo.data.DataSource({
transport: {
read: {
url: "/Home/GetStudents",
dataType: "json"
}
},
pageSize: 10,
schema: {
model: {
id: "Id",
fields: {
Id: { editable: false, nullable: true },
Name: { validation: { required: true } },
FatherName: { type: "text", validation: { required: true, min: 1 } },
Email: { type: 'email', validation: { min: 0, required: true } },
Address: { type: "text", validation: { min: 0, required: true } },
ContactNo: { type: 'text', validation: { min: 0, required: true } },
}
},
parse: function (data) {
debugger
if (!data.success && typeof data.success !== 'undefined') {
gridDataSource.read();
}
if (data.success) {
viewModel.gridDataSource.read();
}
return data;
}
}
}),
});
kendo.bind($("#grid-container"), viewModel);
});
</script>
*Global variable
isExport = false;
data-bind="source: dataSource,events:{excelExport : onExcelExport}"
onExcelExport: function (e) {
var sheet = e.workbook.sheets[0];
for (var rowIndex = 1; rowIndex < sheet.rows.length; rowIndex++) {
var row = sheet.rows[rowIndex];
for (var cellIndex = 0; cellIndex < row.cells.length; cellIndex++) {
if (cellIndex === 6 || cellIndex === 8 || cellIndex === 20)
row.cells[cellIndex].format = "HH:mm"
}
}
var gridcolumn = e.sender.columns;
if (!isExport) {
$.each(gridcolumn, function (index, value) {
if (value.hidden)
e.sender.showColumn(index);
else if (value.hidden === false)
e.sender.hideColumn(index);
e.sender.hideColumn(0);
});
e.preventDefault();
isExport = true;
setTimeout(function () {
e.sender.saveAsExcel();
});
} else {
$.each(gridcolumn, function (index, value) {
if (value.hidden === false)
e.sender.hideColumn(index);
else
e.sender.showColumn(index);
});
isExport = false;
}
},
I am trying to load grid in as a item panel with ajax call. My grid is not loading. Can you please help me. This is I am trying because I was not getting scope in ext ajax call.
My code is
{
xtype: 'panel',
title: "Search Result",
height:500,
items: [
Ext.Ajax.request({
url: 'XML/1Cohart.xml',
scope: this,
timeout: global_constants.TIMEOUT,
method: "GET",
disableCaching: true,
failure: function(response) {
utils.showOKErrorMsg(sdisMsg.ajaxRequestFailed);
},
success: function(response) {
debugger;
var datas = response.responseXML;
Ext.each(datas.getElementsByTagName("HEADER"), function(header) {
this.buildField(header);
this.buildColumn(header);
}, this);
Ext.each(datas.getElementsByTagName("G"), function (columnData) {
//debugger;
//this.buildData(columnData);
this.fieldLength = this.fields.length;
this.record = [];
for (i = 0; i < this.fieldLength; i++) {
//debugger;
var fieldName = this.fields[i].name
this.record[i] = columnData.getAttribute(fieldName);
}
this.data.push(this.record);
}, this);
this.store = new Ext.data.ArrayStore({
fields : this.fields
});
this.store.loadData(this.data);
var grid = new Ext.grid.GridPanel({
store: this.store,
flex: 1,
columns: this.columns,
stripeRows: true,
id: 'RID',
autoHeight: true,
//sm: new Ext.grid.Checkbo;xSelectionModel({singleSelect:true}),
frame: true,
});
}
})
]
}]
Actually I was not getting scope so I placed here.
{
xtype: 'panel',
title: "Search Result",
height:500,
items: [{
xtype : 'GridPanel',
store: new Ext.data.ArrayStore({
fields : this.fields
}),
flex: 1,
columns: this.columns,
stripeRows: true,
id: 'RID',
autoHeight: true,
//sm: new Ext.grid.Checkbo;xSelectionModel({singleSelect:true}),
frame: true,
listeners {
afterRenderer : function(){
Ext.Ajax.request({
url: 'XML/1Cohart.xml',
scope: this,
timeout: global_constants.TIMEOUT,
method: "GET",
disableCaching: true,
failure: function(response) {
utils.showOKErrorMsg(sdisMsg.ajaxRequestFailed);
},
success: function(response) {
debugger;
var datas = response.responseXML;
Ext.each(datas.getElementsByTagName("HEADER"), function(header) {
this.buildField(header);
this.buildColumn(header);
}, this);
Ext.each(datas.getElementsByTagName("G"), function (columnData) {
//debugger;
//this.buildData(columnData);
this.fieldLength = this.fields.length;
this.record = [];
for (i = 0; i < this.fieldLength; i++) {
//debugger;
var fieldName = this.fields[i].name
this.record[i] = columnData.getAttribute(fieldName);
}
this.data.push(this.record);
}, this);
});
}
})
}
}
]
}
I import the Excel file to server and the server return the JSON data to client. but after the new JSON data binding to the kendo grid dataSource, I can't update or delete this or these datas? What can I do to resolve this problem?
This is the form submit js code:
var form = $('#idForm');
var grid = $('#demo2').data('kendoGrid');
form.submit(function (e) {
var formData = new FormData($(this)[0]);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: formData,
cache: false,
processData: false,
contentType: false,
dataType: 'json',
//async: false,
success: function (response) {
if (response.result) {
***grid.dataSource.data(response.data);***
$('#moneyin').text(response.context.moneyin);
$('#moneyout').text(response.context.moneyout);
$('#moneyleft').text(response.context.moneyleft);
} else {
alert(response.message);
}
},
error: function (response) {
alert("error");
}
});
//e.preventDefault(); // avoid to execute the actual submit of the form.
return false;
});
var url = site_url + 'inline_edit/';
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: site_url + 'initial/',
type: 'GET',
dataType: "json"
},
update: {
url: url,
type: 'POST',
dataType: 'json'
},
create: {
url: url,
type: 'POST',
dataType: 'json'
},
destroy: {
url: url,
type: 'POST',
dataType: 'json'
},
parameterMap: function (options, operation) {
//if (operation == "read") {
// return {
// page: options.page,
// pageSize: options.pageSize,
// start: $('#start').val(),
// end: $('#end').val()
// }
//}
if (operation !== "read" && options.models) {
for (var k = 0; k < options.models.length; k++) {
var date_str = date2str(options.models[k].date, 'yyyy-MM-dd');
var recor_str = date2str(new Date(), 'yyyy-MM-dd');
options.models[k].date = date_str;
options.models[k].recordate = recor_str;
}
return {
'operation': operation,
'models': kendo.stringify(options.models)
};
}
}
},
requestEnd: function (e) {
if (e.response && e.response.context) {
$('#moneyin').text(e.response.context.moneyin);
$('#moneyout').text(e.response.context.moneyout);
$('#moneyleft').text(e.response.context.moneyleft);
}
},
//serverPaging: true,
batch: true,
pageSize: 7,
schema: {
model: {
id: 'id',
//data type of the field {Number|String|Boolean|Date|datetime} default is String
fields: {
id: {
type: "number",
editable: false,
nullable: false
},
date: {
type: "date",
defaultValue: new Date(),
validation: {
required: true
}
},
fundbefore: {
type: "number",
editable: false,
nullable: true
},
moneyin: {
type: "number",
validation: {
min: 0,
required: true
}
},
moneyout: {
type: "number",
validation: {
min: 0,
required: true
}
},
fundafter: {
type: "number",
editable: false,
nullable: true
},
charge: {
type: "string",
validation: {
required: true
}
},
reason: {
type: 'textarea',
validation: {
required: true
}
},
recordate: {
type: 'date',
editable: false,
defaultValue: new Date()
},
modify: {
editable: false,
defaultValue: user_name
}
}
},
data: function (response) {
if (response.result) {
return response.data;
} else {
return alert(response.message);
}
},
total: function (response) {
return response.total;
}
}
Uncaught TypeError: Cannot read property 'template' of undefined
I am using a kendo grid .
I want to Disable a Column when I edit.(Not when I add a new record).Did write code when edit
function onEdit(e) {
var indexCell = 1;
var grid = $('#consumablesGrid').data('kendoGrid');
if (e.model.id) { // when Editing the id is defined
if (indexCell != 'undefined' && grid.columns[indexCell].title == "Consumable") {
grid.closeCell();
}
}
}
But it shows "Uncaught TypeError: Cannot read property 'template' of undefined " when executing grid.closeCell() .
For better understanding I am Including My full grid Condition.
function ConsumableManager() {
$("#consumablesGrid").kendoGrid({
dataSource: {
transport: {
read: {
url: "GetConsumablesGrid",
type: "POST",
contentType: "application/json",
dataType: "json"
},
update: {
url: "UpdateConsumables",
contentType: "application/json",
type: "POST",
dataType: "json",
complete: function (data) {
var result = jQuery.parseJSON(data.responseText);
if (result.State == true) {
toastr.success(result.Description);
$("#consumablesGrid").data("kendoGrid").dataSource.read();
}
else {
toastr.error(result.Description);
$("#consumablesGrid").data("kendoGrid").dataSource.read();
}
}
},
destroy: {
url: "DestroyConsumables",
contentType: "application/json",
type: "POST",
dataType: "json",
complete: function (data) {
var result = jQuery.parseJSON(data.responseText);
if (result.State == true) {
toastr.success(result.Description);
$("#consumablesGrid").data("kendoGrid").dataSource.read();
}
else {
toastr.error(result.Description);
}
}
},
create: {
url: "CreateConsumables",
contentType: "application/json",
type: "POST",
dataType: "json",
complete: function (data) {
var result = jQuery.parseJSON(data.responseText);
if (result.State == true) {
toastr.success(result.Description);
$("#consumablesGrid").data("kendoGrid").dataSource.read();
}
else {
toastr.error(result.Description);
}
}
},
parameterMap: function (data, operation) {
if (operation != "read") {
return kendo.stringify(data.models);
}
}
},
serverPaging: false,
pageSize: 10,
batch: true,
schema: {
model: {
id: "ConsumablesID",
fields: {
ConsumablesID: { editable: false },
Consumable: { editable: true },
UnitCost: { editable: true },
Currency: { editable: true },
ContractID: { editable: false }
}
},
errors: "Errors"
},
error: function (e) {
alert(e.errors + "grid");
}
},
editable:
{
mode: "inline",
createAt: "bottom"
},
pageable: {
refresh: true,
pageSizes: true
},
toolbar: ["create"],
sortable: true,
autoBind: false,
edit: function (e) {
alert("Edit");
onEdit(e);
},
update: function (e) {
},
columns:
[
{ field: "ConsumablesID", width: 50, hidden: true, title: "ID" },
{ field: "Consumable", width: 200, title: "Consumable", editor: ConsumablesDropDownEditor },
{ field: "UnitCost", width: 100, title: "Unit Cost" },
{ field: "Currency", width: 200, title: "Currency", editor: CurrencyUnitDropDownEditor },
{ field: "ContractID", width: 85, hidden: true, title: "ContractID" },
{ command: ["edit", "destroy"], title: "Action", width: "175px" }
]
});
$("#consumablesGrid").data("kendoGrid").dataSource.read();
}
Anyone have Idea Why this happened.How can I do that Please response.
1.I've a grid
2.I want to editable (False) when edit (Not in add)
You probably have too new a jquery version: http://docs.telerik.com/kendo-ui/getting-started/javascript-dependencies#jquery-version
Current Kendo UI supports jquery 1.9.1. If you use later versions of jquery with kendo you may face issue with closeCell().
To fix(work around) this issue you can use
$('#consumablesGrid').getKendoGrid().trigger('cancel')
instead of grid.closeCell()
It's depend of jquery versions .
To avoid this problem you can use this script
function onEdit(e) {
if (!e.model.isNew() && (e.model != 'undefined') && (e.model != null)) {
e.container.find("input[name=GroupName]").hide(); // To hide only the value of the column when updating the row
// e.container.find("#GroupName").parent().hide().prev().hide(); //to hide completely the column (value + structure + title name)
}
}