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;
}
Related
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>
I am new to jqGrid and I tried to implement inline editing on the same. i could see no error but the rows are not edited and the grid will be in "saving" mode forever once i click submit button. please shed some light on where I am going wrong.
<script type="text/javascript">
$(document).ready(function () {
jQuery("#tabl").jqGrid({
url: "UserDetails.aspx/GetAllRecords",
datatype: "json",
mtype: 'POST',
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
serializeGridData: function (postData) {
//alert(postData);
//alert(JSON.stringify(postData));
return JSON.stringify(postData);
},
jsonReader: {
root: function (obj) {
//alert(JSON.stringify(obj.d));
return typeof obj.d === "string" ? $.parseJSON(obj.d) : obj.d;
},
page: function (obj) { return 1; },
total: function (obj) { return 1; },
records: function (obj) { return obj.d.length; },
id: '0',
cell: '',
caption: "",
repeatitems: false
},
colNames: ['Category', 'ParamCode', 'ParamName', 'Description', 'DefaultValue', 'CompId', 'SiteId', 'SysTerminal', 'UserId', 'LastUpdateDt'],
colModel: [
{ name: 'Category' },
{ name: 'ParamCode' },
{ name: 'ParamName' },
{ name: 'Description' },
{ name: 'DefaultValue' },
{ name: 'QueryCompId', formatter: 'checkbox' },
{ name: 'QuerySiteId', formatter: 'checkbox' },
{ name: 'QuerySysTerminal', formatter: 'checkbox' },
{ name: 'QueryUserId', formatter: 'checkbox' },
{ name: 'LastUpdateDt', formatter: 'date' }
],
multiselect: false,
height: 'auto',
autoencode: true,
rowList: [10, 20, 30],
rowNum: 10,
pager: '#pager',
loadonce: true,
viewrecords: true,
gridview: true,
caption: "",
onCellSelect: function (rowid, iCol, cellcontent, e) {
pCode = cellcontent;
jQuery("#tablParamValues").jqGrid({
url: "UserDetail.aspx/GetParamValues",
editurl: "UserDetail.aspx/EditParamValue",
datatype: "json",
mtype: 'POST',
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
serializeGridData: function (postData) {
//alert(JSON.stringify(postData));
return JSON.stringify({ paramcode: pCode });
},
jsonReader: {
root: function (obj) {
//alert(JSON.stringify(obj.d));
return typeof obj.d === "string" ? $.parseJSON(obj.d) : obj.d;
},
page: function (obj) { return 1; },
total: function (obj) { return 1; },
records: function (obj) { return obj.d.length; },
id: '0',
cell: '',
caption: "Manipulating Array Data",
repeatitems: false
},
colNames: ['ParamValueId', 'ParamCode', 'CompId', 'SiteId', 'SysTerminal', 'UserId', 'ParamValue'],
colModel: [
{ name: 'ParamValueId', index: 'ParamValueId' },
{ name: 'ParamCode' },
{ name: 'CompId' },
{ name: 'SiteId' },
{ name: 'SysTerminal' },
{ name: 'UserId' },
{ name: 'ParamValue', index: 'ParamValue', editable: true }
],
multiselect: false,
height: 'auto',
autoencode: true,
rowList: [10, 20, 30],
rowNum: 10,
pager: '#pager2',
loadonce: false,
viewrecords: true,
gridview: true,
caption: "",
ajaxRowOptions: {
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json"
},
serializeRowData: function (postdata) {
for (propertyName in data) {
if (data.hasOwnProperty(propertyName)) {
propertyValue = data[propertyName];
if ($.isFunction(propertyValue)) {
dataToSend[propertyName] = propertyValue();
} else {
dataToSend[propertyName] = propertyValue;
}
}
}
return JSON.stringify(dataToSend);
}
}).trigger("reloadGrid").inlineNav('#pager2', { edit: true, add: false, del: false, search: false },
{
ajaxEditOptions: { type :"POST",
contentType :"application/json; charset=utf-8",
dataType :"json"
},
serializeEditData: function createJSON(postdata) {
if (postdata.id === '_empty')
postdata.id = null;
return JSON.stringify(postdata)
},
closeAfterEdit: true
}).jqGrid('filterToolbar', { autoSearch: true });
//set width of grid
jQuery("#tablParamValues").jqGrid('setGridWidth', '700');
}
}).navGrid('#pager', { edit: false, add: false, del: false, search: false })
.jqGrid('filterToolbar', { autoSearch: true });
jQuery("#tabl").jqGrid('setGridWidth', '700');
});
</script>
<script type="text/javascript">
$(document).ready(function () {
jQuery("#tblData").jqGrid({
url: "CurrencySetting.aspx/GetAllRecords",
editurl:"CurrencySetting.aspx/EditRecord",
datatype: "json",
mtype: 'POST',
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
serializeGridData: function (postData) {
//alert(postData);
//alert(JSON.stringify(postData));
return JSON.stringify(postData);
},
jsonReader: {
root: function (obj) {
//alert(JSON.stringify(obj.d));
return typeof obj.d === "string" ? $.parseJSON(obj.d) : obj.d;
},
page: function (obj) { return 1; },
total: function (obj) { return 1; },
records: function (obj) { return obj.d.length; },
id: '0',
cell: '',
caption: "",
repeatitems: false
},
colNames: ['Cd', 'Ds', 'Culture', 'DecimalPlaces', 'ShortDescription', 'Rate', 'Symbol', 'DateTimeFormat'],
colModel: [
{ name: 'Cd', formoptions: { rowpos: 1, colpos: 1} },
{ name: 'Ds', formoptions: { rowpos: 1, colpos: 2} },
{ name: 'Culture', formoptions: { rowpos: 1, colpos: 3}, },
{ name: 'DecimalPlaces', formoptions: { rowpos: 2, colpos: 1} },
{ name: 'ShortDescription', formoptions: { rowpos: 2, colpos: 2} },
{ name: 'CurrencyRate', formoptions: { rowpos: 2, colpos: 3} },
{ name: 'Symbol', formoptions: { rowpos: 3, colpos: 1} },
{ name: 'DateTimeFormat', formoptions: { rowpos: 3, colpos: 2} }
],
cmTemplate: { editable: true },
multiselect: false,
height: 'auto',
autoencode: true,
rowList: [10, 20, 30],
rowNum: 10,
pager: '#pager',
loadonce: true,
viewrecords: true,
gridview: true,
sortable: true,
caption: "",
loadComplete: function () {
// alert("OK");
},
loadError: function (jqXHR, textStatus, errorThrown) {
// alert(jqXHR.status + textStatus + errorThrown);
//alert(jqXHR.responseText);
}
}).navGrid('#pager', { edit: true, add: true, del: true, search: false },
{
ajaxEditOptions: { type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json"
},
serializeEditData: function createJSON(postdata) {
if (postdata.id === '_empty')
postdata.id = null;
return JSON.stringify({id:'AED',decPlace:'10'})
},
closeAfterEdit: true}
) .jqGrid('filterToolbar', { autoSearch: true });
//set width of grid
jQuery("#tblData").jqGrid('setGridWidth', '700');
$.extend($.jgrid.view, { width: 450, recreateForm: true });
$.extend($.jgrid.edit, { width: 450, recreateForm: true });
$.extend($.jqgrid.del, {width:300, recreateform:true});
});
$(window).on("resize", function () {
var newWidth = $("#tblData").closest(".ui-jqgrid").parent().width();
$("#tblData").jqGrid("setGridWidth", newWidth, true);
});
</script>
I seem to be having an issue trying to bing my JSON result to my Kendo UI grid
This is my JSON result I get back from my web service:
"{
"Data":[{
"ModifiedBy":"Joe Blogs",
"ModifiedDate":"2015-04-27T00:00:00",
"Name":"One",
"Number":"201504260952",
"Status":"Draft",
"Id":3
},
{
"ModifiedBy":"Joe Blogs",
"ModifiedDate":"2015-07-08T11:04:00",
"Name":"fdasfdsa",
"Number":"20150708110209",
"Status":"Draft",
"Id":17},
{
"ModifiedBy":"Joe Blogs",
"ModifiedDate":"2015-07-09T08:44:00",
"Name":"Two",
"Number":"20150709084329",
"Status":"Draft",
"Id":20
}],
"Groups":null,
"Total":3
}"
This is my Grid and data source set up:
$(function () {
var myGrid = $("#myGrid");
myGrid.kendoGrid({
groupable: true,
sortable: true,
filterable: true,
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
},
columns: [{
hidden: true,
field: "Id"
},
{
headerTemplate: ""
},
{
title: "Status",
field: "Status"
},
{
title: "Number",
field: "Number"
},
{
title: "Name",
field: "Name"
}]
});
var myDataSource = new kendo.data.DataSource({
transport: {
read: {
url: "/somewhere.svc/Data",
dataType: "json",
type: "GET"
}
},
schema: {
data: 'Data',
groups: 'Groups',
aggregates: 'Aggregates',
total: 'Total',
model: {
id: 'Id',
fields: {
Id: { type: 'number' },
Status: { type: 'string' },
Number: { type: 'string' },
Name: { type: 'string' },
ModifiedBy: { type: 'string' },
ModifiedDate: { type: 'date' }
}
}
},
pageSize: 5,
serverPaging: true,
serverGrouping: true,
serverSorting: true,
serverFiltering: true
});
myGrid.data("kendoGrid").setDataSource(myDataSource);
});
When the page loads I can see that I get the above JSON but I don't get any rows displayed in the grid.
What might I be doing wrong?
Ok, so here is the thing... I have grid with 3 columns: Premises Order, Name and Postal Code
The first column Premises Order is editable(numericall). What I want to do is this: Make an onChange function to save the value of the new inserted number. I know I need a procedure for that I just want to know how to catch the value (in console), to know that I have it and than I'll do the procedure.
Here is the code
PremisesGrid2 = $("#assignedRoute").kendoGrid({
dataSource: {
type: "application/jsonp",
transport: {
read:
{
url: "http://" + servername + "/uBillingServices/Premise/Premise.svc/GetAllPremisesByRoute",
dataType: "json",
data: function () {
return {
Route_ID: selectedID,
UserName: userName,
WorkStation: workStation
}
}
}
}, pageSize: 10,
serverPaging: true,
schema: {
model: {
fields: {
ID: { type: "string", validation: { required: true }, editable: false },
PostalCode: { type: "string", validation: { required: true }, editable: false },
Latitude: { type: "string", validation: { required: true }, editable: false },
Longitude: { type: "string", validation: { required: true }, editable: false },
IsMember: { type: "string", validation: { required: true }, editable: false },
Name: { type: "string", validation: { required: true }, editable: false },
RouteOrderBy: { type: "number", validation: { required: true }, editable: true, nullable: false, format: "{0:n2}" }
}
},
data: function (result) {
return result.rows || result;
},
total: function (result) {
var data = this.data(result);
return result.totalRows || result.length || 0; ;
}
}
},
change: onChange,
dataBound: function (e) {
e.sender.select(e.sender.tbody.find(">tr:first"));
},
selectable: "multiple",
scrollable: true,
filterable: true,
editable: true,
groupable: false,
pageable: {
numeric: true,
pageSizes: true,
previousNext: false
},
sortable: {
mode: "single",
allowUnsort: false
},
height: 400,
columns: [
{ field: "RouteOrderBy", title: "Premise Order", headerAttributes: {
style: "font-size:small; text-align:center"
}, attributes: { style: "text-align:right" }
},
{ field: "PostalCode", title: "Assigned Premises", headerAttributes: {
style: "font-size:small; text-align:center"
}
},
{ field: "Name", title: "Customer", headerAttributes: {
style: "font-size:small; text-align:center"
}
}
]
});
Thank you.
Instead of using change event, you should use save. change is fired when there is a change in the selection of a row not in the value.
For displaying the edited value, the HTML element containing the edited value and the item in the model, you can use:
save : function (e) {
console.log("The values entered by the user.", e.values);
console.log("The jQuery element which is in edit mode.", e.container);
console.log("The edited model.", e.model);
},
Another frustrating day with the Kendo Grid. Anyway, my problem is this: When I click "Edit" on a grid row item, it goes into edit mode. Good. Then I modify a record, and click update. I would expect the "/Company/SaveAccountAdmin" method to be called.But no... The read method is called again. When I click "Cancel" the record just disappears! The $("#save") click event is just an attempt to force a save, but surely these events can be triggered off the grid command buttons? Any ideas anyone?
/// <reference path="../kendo.all-vsdoc.js" />
$(document).ready(function () {
var CompanyId = $("#CompanyId").val();
var dataSource = new kendo.data.DataSource(
{
batch: true,
pageSize: 10,
transport: {
create: {
url: "/Company/SaveAccountAdmin",
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json",
url: "/Company/ReadAccountAdmin",
},
read: {
url: "/Company/ReadAccountAdmin"
},
update: {
url: "/Company/SaveAccountAdmin",
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json",
url: "/Company/ReadAccountAdmin",
},
//destroy: {},
parameterMap: function (options, operation) {
if (operation !== "read" && options.model) {
return { model: kendo.stringify(options.model) };
}
}
},
schema: {
model: {
id: "ComanyContactId",
fields: {
CompanyId: { type: "number", editable: false, nullable: false, defaultVaue: CompanyId },
CompanyContactId: { type: "number", editable: false, defaultValue: 0 },
FirstName: { type: "string", nullable: false, validation: { required: true } },
LastName: { type: "string", nullable: false, validation: { required: true } },
Email: { type: "string", nullable: false, validation: { required: true } },
Phone: { type: "string", nullable: false, validation: { required: true } },
IsActive: { type: "boolean" }
}
}
}
});
$("#save").click(function (event) {
event.preventDefault();
var rows = $.map(dataSource.data(), function (value, index) {
return {
CompanyId: value["CompanyId"],
CompanyContactId: value["CompanyContactId"],
FirstName: value["FirstName"],
LastName: value["LastName"],
Email: value["Email"],
Phone: value["Phone"],
IsActive: value["IsActive"]
}
});
var jsonCompanyContacts = JSON.stringify(rows);
$.ajax({
url: '/Company/SaveAccountAdmin',
type: 'POST',
traditional: true,
data: { "jsonCompanyContacts": jsonCompanyContacts },
success: alert("Data Saved")
})
});
$("#AccountAdmins").kendoGrid({
dataSource: dataSource,
toolbar: ["create"],
editable: "inline",
sortable: true,
pageable: true,
navigatable: true,
editable: "inline",
columns: [
{ field: "CompanyId", title: "CompanyID", sortable: true },
{ field: "CompanyContactId", title: "Company ContactID", sortable: true },
{ field: "FirstName", title: "First Name", sortable: true },
{ field: "LastName", title: "Last Name" },
{ field: "Email", title: "Email", },
{ field: "Phone", title: "Phone", },
{ field: "IsActive", title: "Is Active" },
{ command: ["edit", "destroy"], title: " ", width: "210px" }]
});
});
My guess is that it is because you have the Read URL set for the Update command:
update: {
url: "/Company/SaveAccountAdmin", // <-- Not used because it is changed below
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json",
url: "/Company/ReadAccountAdmin", // <-- Read URL set
},