Kendo Grid JSON datasource binding - json

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?

Related

Server side sorting is not working in kendo ui grid

I am trying to apply sorting on all data when i click on Name but sorting operation is applied on first page data.
Here is my code.
$("#products-grid").kendoGrid({
dataSource: {
type: "json",
transport: {
read: {
url: "#Html.Raw(Url.Action("ProductList", "Product"))",
type: "POST",
dataType: "json",
data: additionalData
}
},
schema: {
data: "Data",
total: "Total",
errors: "Errors"
},
pageSize: #(defaultGridPageSize),
serverPaging: true,
// serverFiltering: true,
sort: { field: "Name", dir: "desc" },
},
pageable: true,
sortable: true,
editable: {
confirmation: "#T("Admin.Common.DeleteConfirmation")",
mode: "inline",
},
scrollable: false,
columns: [
{
field: "Name",
title: "#T("Admin.Catalog.Products.Fields.Name")",
sortable: {
initialDirection: "desc"
},
width: 300,
} ]
});
I have also tried with serverSorting: true but at that time default sorting not working.

Kendo grid with default Columns

I want to show to users subset of columns and allow them to add extra columns if needed. I am struggling to load only subset of columns on load. Please find the code below I have done.
<kendo-grid k-options="vm.mainGridOptions"
k-columns="vm.mainGridColumns"
k-sortable="true"
k-filterable="{mode: 'row'}"
k-column-menu="true"
k-serverFiltering="false"
k-pageSize="10"
k-pageable="{ pageSizes: [5, 10, 25, 50, 100] }"> </kendo-grid>
Controller code
var mainGridDataSource = new kendo.data.DataSource({
transport: { read: mainGridReadEventHandler, cache: true },
serverFiltering: false,
page: 1,
pageSize: 10,
schema: {
data: 'data',
total: 'total',
model: {
fields: {
customerName: { type: "string" },
serviceAccountStatus: { type: "string" },
customerNumber: { type: "string" },
serviceType: { type: "string" },
utilityAccountNumber: { type: "string" },
serviceAddress: { type: "string" },
billingAccountNumber: { type: "string" },
utility: { type: "string" },
phoneNumber: { type: "string" },
email: { type: "string" }
}
}
}
});
vm.mainGridColumns = [
{
field: "customerName",
title: "Name",
template:
"<a ui-sref='resiservice.account-search.customer-details({ customerId:${customerId}, serviceAccountId:${serviceAccountId} })'>${customerName}</a>"
},
{
field: "serviceAccountStatus",
title: "Status"
},
{
field: "customerNumber",
title: "NAP Customer #"
},
{
field: "serviceType",
title: "Commodity"
},
{
field: "utilityAccountNumber",
title: "Utility/Account #"
},
{
field: "serviceAddress",
title: "Service Address"
},
{
field: "billingAccountNumber",
title: "NAP Account #"
},
{
field: "utility",
title: "Utility"
},
{
field: "phoneNumber",
title: "Phone #"
},
{
field: "email",
title: "Email Address"
}
];
Currently columns list coming like this first time
And i want to achive like this
Use columns.hidden property to hide a column, i.e.
{
field: "utility",
title: "Utility",
hidden: true
},
{
field: "phoneNumber",
title: "Phone #",
hidden: true
},
{
field: "email",
title: "Email Address",
hidden: true
}
For example:
http://dojo.telerik.com/EzuFO
The column is still visible on the list of columns in menu.

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

onChange function for a specific column in grid

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

Why is my Read Method being called when I click update on the inline editing of a grid row

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
},