Kendo spreadsheet is not binding first time using json - json

I have a kendo spread sheet which is not loading first time in browser after refreshing it will works. I already searched lots of in google but unable to find any solutions.Please help me how to fixed that issue. I am using asp.net mvc.
my spread sheet code is below
var customVal = $("#customInput").data("value");
var CellCount = $('#sessionDivCount').attr('data-id');
var headercount = '1';
var displayCount = Number(CellCount) + Number(headercount);
$(function () {
var shouldPopulateHeader = true;
var dataSource = new kendo.data.DataSource({
requestEnd: function (e) {
setTimeout(function (e) {
if (shouldPopulateHeader) {
shouldPopulateHeader = false;
var spreadsheet = $("#spreadsheet").data("kendoSpreadsheet");
var sheet = spreadsheet.activeSheet();
// Change the default headers for the first and the second column
sheet.batch(function () {
sheet.range("A1").value("Order ID");
sheet.range("D1").value("Check/Receipt/Reference/Confirmation Number");
sheet.range("E1").value("Date Check Was Made Made/Payment Was Maid");
sheet.range("F1").value("Agent Payment Confirmation");
sheet.range("G1").value("Estimated payment Arrival Date");
sheet.range("A1:A16384 ").enable(false);
sheet.range("A2:A16384 ").textAlign = "center";
sheet.range("B1:B16384 ").enable(false);
var range = sheet.range("A2:A16384"); // 2x2 cell range
range.bold = true;
range.textAlign = "center";
range.color("green");
var range1 = sheet.range("B2:B16384"); // 2x2 cell range
range1.bold = true;
range1
range1.textAlign = "center";
range1.color("black");
range1.defaultValue = null;
sheet.range("c2").textAlign = "center";
}, { recalc: true });
}
}, 0);
},
transport: {
read: onRead,
submit: onSubmit
},
batch: true,
change: function () {
$("#cancel, #save").toggleClass("k-state-disabled", !this.hasChanges());
},
schema: {
model: {
OrderID: "OrderID",
fields: {
OrderID: {
type: "number",
defaultValue: null
},
PO: {
type: "string",
defaultValue: null
},
Method: {
type: "string",
},
Check_Receipt_Refernce_confirmation_Number: {
type: "string"
},
DateCheck_Was_Mailed_Payment_Was_Made: {
type: "date"
},
Agent_Payment_Confirmation: {
type: "string"
},
Estimated_Payment_Arrival_Date: {
type: "date"
},
}
}
}
});
$("#spreadsheet").kendoSpreadsheet({
columns: 7,
rows: displayCount,
toolbar: true,
sheetsbar: false,
sheets: [{
name: "Products",
dataSource: dataSource,
rows: [{
height: 20,
cells: [
{
value: "Order ID",
bold: "true",
background: "#9c27b0",
textAlign: "center",
color: "white",
hidden: true,
enable: false
}, {
bold: "true",
background: "#9c27b0",
textAlign: "center",
color: "white",
enable: false
}, {
bold: "true",
background: "#9c27b0",
textAlign: "center",
color: "white",
enable: false
}, {
bold: "true",
background: "#9c27b0",
textAlign: "center",
color: "white",
enable: false
},
{
bold: "true",
background: "#9c27b0",
color: "white",
textAlign: "center",
enable: false
},
{
bold: "true",
background: "#9c27b0",
textAlign: "center",
color: "white"
}, {
bold: "true",
background: "#9c27b0",
textAlign: "center",
color: "white"
}
]
}],
columns: [
{ width: 145 },
{ width: 145 },
{ width: 145 },
{ width: 300 },
{ width: 300 },
{ width: 300 },
{ width: 300 }
]
}]
});
function onSubmit(e) {
var arrofId = new Array();
var models = {};
var obj = "";
for (i = 0; i < JSON.stringify(e.data.created.length); i++) {
obj = e.data.created[i];
arrofId.push(obj);
}
arrofId.push(obj);
$.ajax({
type: "POST",
url: "/Agent/GetDataSpreadSheetSubmit1",
data: '{models: ' + JSON.stringify(arrofId) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert('Record Saved Succesfully');
$('#grid').data('kendoGrid').dataSource.read();
$('#grid').data('kendoGrid').refresh();
},
error: function (xhr, httpStatusMessage, customErrorMessage) {
alert(xhr.responseText);
}
});
}
function onRead(options) {
$.ajax({
url: "../Agent/GetDataSpreadSheet",
type: "get",
dataType: "json",
success: function (result) {
debugger
options.success(result.data);
$("#spreadsheet").data("kendoSpreadsheet").refresh();
},
error: function (result) {
options.error(result);
}
});
}
$("#save").click(function () {
debugger
if (!$(this).hasClass("k-state-disabled")) {
dataSource.sync();
}
});
$("#cancel").click(function () {
if (!$(this).hasClass("k-state-disabled")) {
dataSource.cancelChanges();
}
});
});
}
any my controller action method for getting the list is below
[HttpGet]
public ActionResult GetDataSpreadSheet()
{
int statusID = 50;
var list = agentLogic.GetListByStatusID_forSpreadSheet(statusID).OrderBy(p => p.OrderID).ThenBy(o => o.OrderID);
HttpContext.Session["CheckSpreadsheetCount"] = list.Count();
return Json(new { total = list.Count(), data = list }, JsonRequestBehavior.AllowGet);
}
kendo spread sheet is not loading first time but after reload the browser its works as expected. Please help me what should i do? Please help me i am still unable to find any solution when it loads first time in any browser it creates problem after refresh it's working as expected.

Related

KendoGrid: can't disable autosync + all other lines are disabled after "destroy"

I tried so solve this for a while now, but cannot find the solution.
I cannot disable autosync for some reason. Everytime I click on "destroy" for a single row, transport.submit is triggered (and would send data to the server). I actually only want to trigger submit once, when I click the "save" button.
Is this expected behaviour? Should I handle the server communications externaly and only save locally in transport.submit? Or am I doing something wrong?
Once I remove one item using the "destroy" button, all other items are disabled until I press the "cancel" button.
How can I avoid this?
Here is my Code:
$(document).ready(function () {
var myData = getDataSource();
var dataGrid = $("#divOverview").kendoGrid({
dataSource: myData,
sortable: true,
filterable: true,
pageable: true,
toolbar: ["save", "cancel"],
columns: [
// Dataworld
{ field: "Dataworld", width: "180px" },
// Servername
{ field: "Servername"},
// IPAddress
{ field: "IPAddress"},
// Commands
{ command: ["destroy"], title: " ", width: "250px" }
],
editable: {
mode: "inline",
confirmation: false
}
});
});
function getDataSource(){
var datasource = new kendo.data.DataSource({
transport: {
read: function(options) {
$.ajax({
url: "../AccountSyncConfig/GetAccountSyncConfig.erb",
dataType: "json",
data: {mandatorID: mandatorID},
success: function(result) {
options.success(result);
},
error: function(result) {
options.error(result);
}
});
},
submit: function(e) {
var data = e.data;
console.log(data);
},
parameterMap: function(data, type) {
if (type == "read") {
return { mandatorID: mandatorID};
} else if (type == "submit") {
//console.log( {models: JSON.stringify(data.models)} );
return {
data: kendo.stringify({
mandatorID: mandatorID,
models: data.models
})
};
} else {
return "";
}
}
},
schema: {
model: {
id: "EntryID",
fields: {
Dataworld: {
type: "string",
validation: {
required: true
}
},
Servername: {
type: "string",
validation: {
required: true
}
},
IPAddress: {
type: "string",
validation: {
required: true,
IPAddressvalidation: function (input) {
if (input.val() != "") {
input.attr("data-IPAddressvalidation-msg", "Ungültige IP-Adresse");
return /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(input.val());
}
return true;
}
}
}
},
}
},
autoSync: false,
batch: true,
pageSize: 10
});
return datasource;
}

Using Chart JS in Asp.net MVC

I have a table having no of files and their month. i want to show line chart for progress of every month. but i am not able to show the data in the chart,
in console.log date is also not in the required form. how should i put month names which are generated from the sql query on label fields and and every month counting of file on the data
DataSet ds = dbop.GetViews();
List<ListReg> list = new List<ListReg>();
foreach (DataRow dr in ds.Tables[0].Rows)
{
list.Add(new ListReg
{
eFile_registered = Convert.ToInt32(dr["eFile_registered"]),
eFile_Month = Convert.ToDateTime(dr["eFile_Month"]).ToString()
});
}
return Json(list, JsonRequestBehavior.AllowGet);`
//model
$(document).ready(function () {
$.ajax({
type: "POST",
url: "/test/LineChart",
method: 'GET',
dataType: "JSON",
success: function (dr) {
console.log(dr);
var month=dr[0];
var count=dr[1];
var ctx = document.getElementById("canvas").getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
height: "230px",
width: "300px",
responsive: false,
animation: false,
legend: { position: 'bottom' },
data: {
//labels: ["M", "T", "W", "T", "F", "S", "S"],
labels: month,
datasets: [{
label: 'Monthly Expenses',
data: count,
backgroundColor: "rgb(66, 134, 244)"
}]
}, options: {
events: ['click'],
scaleShowValues: true,
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}],
xAxes: [{
ticks: {
autoSkip: false
}
}]
}
}
});
},
"error": function (list) {
alert("Some Error Occured!");
}
});
})

Prevent datasource reloading on change event of kendo grid

I am working on Kendo Grid, On button click, I call a function to reFetch data from db with new Parameters.
function is here
vm.refereshFigure = function (response) {
vm.gridOptions = {
datasource: new kendo.data.DataSource({
type: "odata",
transport: {
read: function (options) {
if (!!$scope.figure.figureId) {
gridService.runQuery(options, $scope.figure.figureId, response).then(function (responseData) {
options.success(responseData.data);
});
}
}
},
schema: {
data: "Data",
total: "Total"
},
change: function (e) {
debugger;
e.preventDefault();
},
pageSize: vm.gridConfigurationJson.PageSize ? vm.gridConfigurationJson.PageSize : 10,
group: vm.JsonGroupingCloumns,
aggregate: vm.aggregatesList,
serverPaging: true,
serverSorting: true,
serverFiltering: true,
filter: !!vm.gridConfigurationJson.Filter
? vm.gridConfigurationJson.Filter.filters
: vm.gridConfigurationJson.Filter,
page: vm.gridConfigurationJson.page,
sort: vm.gridConfigurationJson.sort
}),
dataBound: function (e) {
//if (vm.gridConfigurationJson.PageSize != e.sender.pager.dataSource._pageSize) {
// saveGridConfigration(e);
//}
},
groupable: true,
pageable: {
refresh: true,
pageSizes: [10, 25, 50, 100, 200, "All"],
buttonCount: 5,
},
noRecords: true,
filterable: true,
sortable: {
mode: "multiple",
allowUnsort: true,
showIndexes: true
},
resizable: true,
reorderable: true,
columnMenu: true,
columns: vm.columnsList,
toolbar: ["excel"],
excel: {
allPages: true,
filterable: true,
},
excelExport: function (e) {
try {
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 (this.columns[cellIndex].type == 'date') {
row.cells[cellIndex].format = "yy-MM-dd hh:mm:ss";
row.cells[cellIndex].value =
kendo.parseDate(row.cells[cellIndex].value, "yyyy-MM-ddTHH:mm:ss");
}
}
}
} catch (e) {
}
var filename = "";
if ($scope.figure.captionView != undefined) {
filename = $scope.figure.captionView;
} else if ($scope.figure.caption != undefined) {
filename = $scope.figure.caption;
}
e.workbook.fileName = filename + ".xlsx";
},
};
$scope.filterChanged(response, undefined, $scope.figure.figureId);
};
It called web api two times. Below is the code in read function which executes two times.
if (!!$scope.figure.figureId) {
gridService.runQuery(options, $scope.figure.figureId, response).then(function (responseData) {
options.success(responseData.data);
});
}
After first Call, It goes Change() event, then call read() again.
Can anyone help me what I am doing wrong?

Pagination using kendo grid does not work on page load

In my js. i am loading data using kendoGridOptions. I have mapped the data source which fetches all the records. I have configured pageable = true. However noticed that when page load the pagination option are not available they become available only on when i sort one of the columns. following is the configuration of my grid and data source
var enhancedGridOptions = mydataKendoGridManager.kendoGridOptions({
dataSource: myGridDataSource,
sortable: true,
scrollable: true,
editable:false,
resizable: true,
reorderable: true,
pageable: true,
columnResize: function (e) {
adjustLastColumn(e, this);
},
columns:
[
{
field: "dealType",
title: $.i18n.prop('buyType.label'),
width: "108px"
},
{
field: "myStatus",
title: $.i18n.prop('myStatus.label'),
width: "105px"
},
{
field: "action",
title: $.i18n.prop('action.label'),
width: "105px"
},
],
pdf:
{
fileName: "my_List_" + (new Date()).toString(myformat + "_HH:mm") + ".pdf",
allPages: true,
},
excel:
{
fileName: "my_List_" + (new Date()).toString(myformat + "_HH:mm") + ".xlsx",
allPages: true,
}
}
and my data source is configured as below
transport: {
read: function (e) {
myapi.rootGet("data/mylist?dealId=" + id, function (response) {
var data;
// console.log(response.data)
if (_.isString(response.data)) {
response.data = JSON.parse(response.data);
data = response.data;
setTimeout(function () {
e.success(data);
}, 10000);
}
else {
e.error("XHR response", response.status, JSON.parse(response.data));
}
});
},
},
schema:
{
model: {
id: "id",
fields: {
dealType: {
type: "string"
},
myStatus: {
type: "string"
},
action: {
type: "string"
},
}
},
parse:function(data)
{
return parseData(data);
}
},
serverSorting: false,
serverFiltering: false,
serverPaging: false
};
appreciate if someone can guide what is missing on pagination that does not work on page load.
Thanks,
Anjana
If you are getting "NaN - NaN of 500 items" like error at left bottom corner in grid, then you should add pageSize in dataSource Property.
var enhancedGridOptions = mydataKendoGridManager.kendoGridOptions({
dataSource: {
data: myGridDataSource,
pageSize: 50
},
....
....
....
pageable: {
pageSizes: [20, 30, 50, 100],
buttonCount: 5
}
});

Kendo Grid - how to remember selected row?

http://dojo.telerik.com/eWakO
Kendo Grid - here how should i modify above code to remember selected row? Example, if i have highlighted 4th row on 1st page and then scrolls to pages and come back to 1st page, then 4th row should be highlighted.
Thanks
Datha
Here is an example from the documentation:
http://docs.telerik.com/kendo-ui/controls/data-management/grid/how-to/Selection/persist-row-selection-while-paging
It relies on the change and dataBound events to save and restore selected rows by their IDs.
<div id="grid"></div>
<script>
$(function () {
var selectedOrders = [];
var idField = "OrderID";
$("#grid").kendoGrid({
dataSource: {
type: "odata",
transport: {
read: "http://demos.kendoui.com/service/Northwind.svc/Orders"
},
schema: {
model: {
id: "OrderID",
fields: {
OrderID: { type: "number" },
Freight: { type: "number" },
ShipName: { type: "string" },
OrderDate: { type: "date" },
ShipCity: { type: "string" }
}
}
},
pageSize: 10,
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
height: 400,
selectable: "multiple",
pageable: {
buttonCount: 5
},
sortable: true,
filterable: true,
navigatable: true,
columns: [
{
field: "ShipCountry",
title: "Ship Country",
width: 300
},
{
field: "Freight",
width: 300
},
{
field: "OrderDate",
title: "Order Date",
format: "{0:dd/MM/yyyy}"
}
],
change: function (e, args) {
var grid = e.sender;
var items = grid.items();
items.each(function (idx, row) {
var idValue = grid.dataItem(row).get(idField);
if (row.className.indexOf("k-state-selected") >= 0) {
selectedOrders[idValue] = true;
} else if (selectedOrders[idValue]) {
delete selectedOrders[idValue];
}
});
},
dataBound: function (e) {
var grid = e.sender;
var items = grid.items();
var itemsToSelect = [];
items.each(function (idx, row) {
var dataItem = grid.dataItem(row);
if (selectedOrders[dataItem[idField]]) {
itemsToSelect.push(row);
}
});
e.sender.select(itemsToSelect);
}
});
});
</script>