Kendo Grid - how to remember selected row? - kendo-grid

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>

Related

Problem in binding the data to the kendo multi-select dropdown

I have a kendo grid in angular, which is supposed to have some columns with multi-select dropdown.
When I select the item from the list for the first time, that item gets binded and the second item when selected the gridParams holds the second item selected, but once the API call returns the data, the list binded refreshes to none(no data binded to the dropdownlist).
Below is the code related
{
OC.setReportGridColumns(responsecolumns);
OC.reportsGridOptions = {
dataSource: {
schema: {
data: "Data",
total: "Total",
model: {
fields: OC.GetSchemaFields()
}
},
transport: {
read: function (e) {
gridParams = JSON.parse(JSON.stringify({
CurrentPage: e.data.page,
PageSize: e.data.pageSize,
Sort: e.data.sort,
Filter: e.data.filter
}));
if (gridParams.Filter != undefined) {
var a;
if (gridParams.Filter.filters!= undefined) {
angular.forEach(gridParams.Filter.filters, function (value, key) {
if (value.field === "QuoteStatus") {
value.operator = "in";
a = "'" + value.value + "'";
a = a.replace(",", "','");
value.value = a;
}
});
};
};
ReportService.GetAllAdHocReport(gridParams, '', OC.CustomColumnSelected, TemplateId).then(function (response) {
if (response != '') {
$("li [ui- sref='AdHocReport']").parent().addClass("activelist");
response.Total = response.Data != null && response.Data.length > 0 ? response.Data[0].TotalRecords : 10;
OC.GridConfigDataSource.read();
e.success(response);
OC.hideFilters();
} else {
e.success([]);
}
});
},
},
filterable: {
mode: "row,menu",
extra:false
},
selectable: 'cell',
columns: OC.gridCols,
}
}
}
OC.setReportGridColumns = function (colList) {
var col = JSON.parse(colList).columns;
OC.setfilterDropdown(col);
var cols = col.map(function (value) {
if (value.column == "QuoteStatus") {
return {
field: value.column,
title: value.title,
filterable: OC.filterDropdowns(value.column),
width: value.width,
sortable: true,
};
}
});
}
OC.filterDropdowns = function (column) {
return {
extra: false,
mode: "menu",
multi: true,
cell: {
showOperators: false,
template: function (args) {
/////------****Multi-select Dropdown****------///////
args.element.kendoMultiSelect({
autoBind: true,
dataTextField: "text",
dataValueField: "value",
dataSource: new kendo.data.DataSource({
data: OC.getDataForFilterDropdown(column)
}),
index: 0,
optionLabel: {
text: "--Select--",
value: ""
},
valuePrimitive: true,
});
},
}
}
}

Kendo spreadsheet is not binding first time using 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.

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 cell editing value does not persist

I have kendo grid which first column is editable, but if i click the column and do change the value and click on a different row, it rolls back the change. I need to click the same row again to have it persist.
public createAppliedDesignGrid(gridSelector: string, isDetail: bool, rowData: any) {
var self = this;
var rowTemplate = (isDetail) ? "#rowAppliedRuleProgramDetailTemplate" : "#rowAppliedRuleProgramTemplate";
var designItemSchema = API.Schema.DesignItemModel();
designItemSchema.gridcolumns[2] = {
hidden: true,
command: {
name: "remove", text: "remove", click: function (e) {
e.preventDefault();
var uid = $(e.currentTarget).closest("tr").data('uid');
var dataItem = this.dataSource.getByUid(uid);
if (dataItem != null) {
// alert("Remove" + dataItem.Id);
//self.ShowAppliedRulesModal(dataItem.Id, dataItem.DesignTypeId);
self.RemoveAppliedDesign(self, dataItem);
self.bumpDesignPriority(null, dataItem.DesignTypeId, dataItem.Priority.valueOf(), 999999);
this.dataSource.remove(dataItem);
}
}
}, title: " ", width: "0px"
};
designItemSchema.gridcolumns[3] = {
hidden: true,
command: {
text: "Select", click: function (e) {
e.preventDefault();
var uid = $(e.currentTarget).closest("tr").data('uid');
var dataItem = this.dataSource.getByUid(uid);
if (dataItem != null) {
//alert("Show popup for " + dataItem.Id);
self.ShowAppliedRulesModal(dataItem.Id, dataItem.DesignTypeId);
}
}
}, title: " ", width: "0px"
};
var options = {
dataSource: {
type: "json",
transport: {
read: function (options) {
if (self.ViewModel().Id == undefined) {
options.success({ data: [], total: 0 });
return;
}
if (options.data.filter == null) {
options.data.filter = {
logic: "and",
filters: new Array()
};
}
if (rowData != null) {
options.data.filter.filters.push({ field: "ParentProgramId", operator: "eq", value: rowData.Id });
if (rowData.ImportedDesignId != null)
options.data.filter.filters.push({ field: "ImportedDesignId", operator: "eq", value: rowData.ImportedDesignId });
if (rowData.DesignTypeId != null)
options.data.filter.filters.push({ field: "DesignTypeId", operator: "eq", value: rowData.DesignTypeId });
}
$.ajax("/API/DesignItem/?$context=KendoGrid&$vm=KendoDesignItemChildren",
{
dataType: 'json',
data: options.data,
cache: false,
success: function (result) {
options.success(result);
}
});
}
},
schema: designItemSchema,
serverFiltering: true,
serverPaging: true,
pageSize: 50,
sort: { field: "Priority", dir: "asc" }
},
// scrollable: true,
scrollable: {
virtual: false
},
pageable: { pageSizes: false, numeric: false },
columns: designItemSchema.gridcolumns,
editable: true,
sort: { field: "Priority", dir: "asc" },
//detailInit: function (e) { return self.appliedDesignDetail(self, e); },
//autoBind: isDetail ? true : false
//, rowTemplate: kendo.template($(rowTemplate).html())
};
return options;
}
public static DesignItemModel() {
var columns = new Array(
{ field: 'Priority', width: '10%', title: '' },
{ field: 'Name', width: '90%', title: 'Name' }
);
var schema: IKendoSchema = {
data: "data",
total: 'total',
batch: true,
model: {
id: "Id",
fields: {
Id: { type: "int", editable: false },
Name: { type: "string", editable: true },
Description: { type: "string", editable: false },
DesignTypeId: { type: "int", editable: false },
FormularyTypeId: { type: "int", editable: false },
PBMId: { type: "int", editable: false },
StartDate: { type: "datetime", editable: false },
EndDate: { type: "datetime", editable: false },
IsClientProgram: { type: "bool", editable: false },
IsAvailableToAllClients: { type: "bool", editable: false },
Priority: { type: "int", editable: true },
HasApprovedVersion: { type: "bool", editable: false },
ImportedDesignId: { type: "int", editable: false }
}
},
gridcolumns: columns
}
return schema;
}