How do I bind the results of an AJAX GET call to a Kendo Grid? - ajax

Refer to the comment inside the AJAX done function below:
$("<div/>").appendTo(e.detailCell).kendoGrid({
reorderable: true,
resizable: true,
dataSource: {
transport: {
read: function()
{
$.ajax({
url: "http://x/y/api/Awards/directors/" + e.data.AwardTitleId,
type: "GET"
}).done(function()
{
//I'm not sure what to do here in order to bind the data returned by the GET to the grid.
});
},
},
schema: {
model: {
id: "namefirstlast",
fields: {
"namefirstlast": { editable: true, type: "string" },
"directorsequence": { editable: true, type: "number", validation: { min: 1 } },
"isonballot": { editable: true, type: "boolean" },
"concatenation": { editable: true, type: "string" },
"MoreNames": { editable: true, type: "number", validation: { min: 0 } },
},
},
}
},
columns: [
{ field: "namefirstlast", title: "Name", editor: namesAutoComplete },
{ field: "directorsequence", title: "Director Sequence", format: "{0:n0}" },
{ field: "isonballot", title: "On ballot?" },
{ field: "concatenation", title: "Concatenation" },
{ field: "MoreNames", title: "More names?", format: "{0:n0}" },
{ command: ["edit"], title: " ", width: 100 }],
sortable: true,
sort: { field: "namefirstlast", dir: "desc" },
editable: "inline",
toolbar: [{ name: "create", text: "Add New Director/Recipient" }]
});

Figured it out:
detailRow.find(".directorsOrRecipients").data("kendoGrid").dataSource.read();
detailRow.find(".directorsOrRecipients").data("kendoGrid").refresh();

Related

kendo grid server re filtering the data source

$(document).ready(function () {
var agenciesData = new kendo.DataToken.DataSource({
type: 'webapi',
transport: {
read: { url: "/api/Agencies/", dataType: "json", data: { activity: getActivity() } },
create: { url: "/api/Agencies", type: "POST", dataType: "json" },
destroy: { url: "/api/Agencies/{0}", type: "DELETE" },
update: { url: "/api/Agencies/{0}", type: "PUT" },
idField: "ID"
},
filter: [{ field: "Activity", operator: "eq", value: getActivity() }],
pageSize: 15,
page: 1,
total: 0,
serverPaging: true,
serverSorting: true,
serverFiltering: true,
schema: {
data: "Data",
total: "Total",
model: {
id: "ID",
fields: {
ID: { editable: false, type: "number" },
AgencyName: { type: "string" },
AgentName: { type: "string" },
Address: { type: "string" },
City: { type: "string" },
Tel1: { type: "string" },
Tel2: { type: "string" },
Pele: { type: "string" },
Activity: { type: "number" },
ToDate: { type: "date" }
}
}
}
});
$("#agenciesGrid").kendoGrid({
dataSource: agenciesData,
toolbar: [{ text: "valid", className: "validAgents" }, { text: "not valid", className: "notValid" }, { text: "all", className: "allAgents" }, { text: "potential", className: "potetial" }],
editable: false,
navigatable: true,
sortable: true,
autoBind: false,
height: 430,
pageable: { refresh: true },
columns: [
{ field: "ID", hidden: true },
{ field: "AgencyName", title: "agency", width: 150, filterable: { cell: { operator: "contains" } } },
{ field: "AgentName", title: "agent", width: 150, filterable: { cell: { operator: "contains" } } },
{ field: "Address", title: "address", width: 200, template: "#= Address + ' ' + City #", filterable: false },
{ field: "Tel1", title: "phones", width: 300, template: "#= Tel1 + ' : ' + Tel2 + ' : ' + Pele #", filterable: false },
{ field: "Activity", title: "active", width: "90px" },
{ field: "ToDate", title: "end Contract", type: "date", width: 90, format: "{0:dd/MM/yyyy}", parseFormats: ["yyyy-MM-ddThh:mm:ss"] }
]
});
$(".validAgents").click(function () { //valid
$("#myActivity").val("1");
$('#agenciesGrid').data().kendoGrid.dataSource.read({ activity: "1" });
});
$(".notValid").click(function () {//notValid
$("#myActivity").val("2");
$('#agenciesGrid').data().kendoGrid.dataSource.read({ activity: "2" });
});
$(".potetial").click(function () {//potetial
$("#myActivity").val("3");
$('#agenciesGrid').data().kendoGrid.dataSource.read({ activity: "3" });
});
});
function getActivity(){
var myActivity = $("#myActivity").val();
return myActivity;
}
When I use kendo grid already filtered by parameter like : $('#someGrid').data().kendoGrid.dataSource.read({ activity: value });
i see the get: https://localhost:44305/api/Agencies/?sort=&page=1&pageSize=15&group=&filter=&activity=1
The grid is filter as expected but, when I want to do paging, sorting, refresh - I get the whole data ignoring the filter that i made.
and I see the get: https://localhost:44305/api/Agencies/?sort=&page=1&pageSize=15&group=&filter=
How can I save my filter state to do paging and sorting on the data came from the server side ?
even when i used differen approach like "scrollable: { virtual: true }" and when i scroll down - every request is without the filtering...
Thanks
Did you try
var agenciesData = new kendo.DataToken.DataSource({
filter : function () {
return object;
}
});
I mean try using filter as a function and you can do your logic inside the function depending on the situation.

Kendo-grid locked column and grouping

I have grid with locked (frozen) column and grouping like this:
demos.telerik.com/kendo-ui/grid/frozen-columns
But I have only one frozen column and small width.
And when I group by column with long string values (eg ship address), these group values in group header displayed in multiple lines.
Screen
How show group header in one line even if first part of grid (with locked columns) has small width?
Source
$(document).ready(function() {
$("#grid").kendoGrid({
dataSource: {
type: "odata",
transport: {
read: "http://demos.telerik.com/kendo-ui/service/Northwind.svc/Orders"
},
schema: {
model: {
fields: {
OrderID: { type: "number" },
ShipCountry: { type: "string" },
ShipName: { type: "string" },
ShipCity: { type: "string" },
ShipAddress: { type: "string" }
}
}
},
pageSize: 30,
group: { field: "ShipName" }
},
height: 540,
sortable: true,
reorderable: true,
groupable: true,
resizable: true,
filterable: true,
columnMenu: true,
pageable: true,
columns: [ {
field: "OrderID",
title: "Order ID",
locked: true,
lockable: false,
width: 50
}, {
field: "ShipCountry",
title: "Ship Country",
width: 300
}, {
field: "ShipCity",
title: "Ship City",
width: 300
},{
field: "ShipName",
title: "Ship Name",
width: 300
}, {
field: "ShipAddress",
width: 400
}
]
});
});
SOLUTION
Alexander Popov from telerik write this:
$(document).ready(function() {
$("#grid").kendoGrid({
dataBound: function(e){
var grid = this;
this.lockedTable.find(".k-grouping-row").each(function(index) {
var arrow = $(this).find("a");
grid.tbody.find(".k-grouping-row:eq("+index+") td").text($(this).text())
$(this).find("p").text(" ").append(arrow);
})
},
dataSource: {
type: "odata",
transport: {
read: "http://demos.telerik.com/kendo-ui/service/Northwind.svc/Orders"
},
schema: {
model: {
fields: {
OrderID: { type: "number" },
ShipCountry: { type: "string" },
ShipName: { type: "string" },
ShipCity: { type: "string" },
ShipAddress: { type: "string" }
}
}
},
pageSize: 30
},
height: 540,
sortable: true,
reorderable: true,
groupable: true,
resizable: true,
filterable: true,
columnMenu: true,
pageable: true,
columns: [ {
field: "OrderID",
title: "Order ID",
locked: true,
lockable: false,
width: 50
}, {
field: "ShipCountry",
title: "Ship Country",
width: 300
}, {
field: "ShipCity",
title: "Ship City",
width: 300
},{
field: "ShipName",
title: "Ship Name",
width: 300
}, {
field: "ShipAddress",
lockable: false,
width: 400
}
]
});
});

Passing KENDO Grid data view to MVC controller

I have an issue sending Telerik Kendo Grid viewdata to MVC Controller. I've tried to make ViewModel etc but i just can't figure this one out.
Here is my code to populate grid:
var grid = $("#grid").kendoGrid({
dataSource: {
data: kontdata.Data,
schema: {
model: {
fields: {
Id: { type: "number", editable: false },
Name: { type: "string" },
Number: { type: "string" },
Info: { type: "string" },
Email: { type: "string" },
Category: { type: "string" },
MarketingAllowed: { type: "number", editable: false },
AddedDate: { type: "date", editable: false }
}
}
},
pageSize: 20
},
height: 500,
scrollable: true,
toolbar: kendo.template($("#template").html()),
serveroperation: false,
sortable: true,
editable: { mode: "incell", confirmation: false },
selectable: "row",
filterable: true,
pageable: true,
columns: [
{
field: "Name",
title: "Nimi"
},
{
field: "Number",
title: "Numero"
},
{
field: "Info",
title: "Info"
},
{
field: "Email",
title: "Email"
},
{
field: "Category",
title: "Kategoria"
},
{
field: "MarketingAllowed",
title: "Markkinointikielto",
width: "160px"
},
{
field: "AddedDate",
title: "LisÀttyPvm",
format: "{0:dd/MM/yyyy HH:mm:ss}"
},
{
command: [
{ name: "destroy", text: "Poista", width: "70px" }
]
}
]
}).data("kendoGrid");
And here is the code to post grid view data:
function tallennagridi() {
var griddata = $("#grid").data("kendoGrid");
$.ajax(
{
type: 'POST',
url: '/Contactlist/Savegriditems/',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ griditems: griddata.dataSource.view() }),
success: function (result) {
alert('success');
}
});
};
And here is the controller:
public JsonResult Savegriditems([DataSourceRequest] DataSourceRequest request, CustomerViewModel griditems)
{
var joku = griditems;
return Json(joku, "Content-type: text/x-json; charset=utf-8", JsonRequestBehavior.AllowGet);
}
Any help would be appreciated.
Br. Eero
My mistake, CustomerViewModel gridItems should have been:
CustomerViewModel[] gridItems;

kendo ui model is always null in parameter map

Im using kendo ui grid and everything is working fine except for update. When i click on the reviewed column the field changes to a check box and i can edit it, and the update gets called but no data is passed in the put request. If i put a breakpoint in the parameter map function the model is null. Javascript code is below:
var selfPayDataSource = new kendo.data.DataSource({
serverFiltering: true, // <-- Do filtering server-side
serverPaging: true, // <-- Do paging server-side
serverSorting: true,
autoSync: true,
pageSize: 100,
batch:false,
//filter: generateDsFilter(),
type: 'odata', // <-- Include OData style params on query string.
sortable: {
mode: "multiple",
allowUnsort: true
},
pageable: {
refresh: true
},
schema: {
data: function (data) {
return data.Items; // <-- The result is just the data, it doesn't need to be unpacked.
},
total: function (data) {
return data["Count"]; // <-- The total items count is the data length.
},
model: {
id: "SelfPayId",
fields: {
resp_ind: { type: "string", editable: false },
cstsv_resolved: { type: "string", editable: false },
cstsv_rep: { type: "string", editable: false },
cstsv_comp_date: { type: "string", editable: false },
region: { type: "string", editable: false },
db: { type: "string", editable: false },
personid: { type: "string", editable: false },
legacyid: { type: "string", editable: false },
account__: { type: "string", editable: false },
deceased: { type: "string", editable: false },
patient_name: { type: "string", editable: false },
account_balance: { type: "number", editable: false },
pat_last_paid_date: { type: "date", editable: false },
pat_last_paid_amt: { type: "number", editable: false },
acct_stat: { type: "string", editable: false },
bill_type: { type: "string", editable: false },
acct_score: { type: "number", editable: false },
tu_status: { type: "string", editable: false },
scoring: { type: "number", editable: false },
coll_ltr: { type: "string", editable: false },
HighestPriPlan: { type: "string", editable: false },
HighestSecPlan: { type: "string", editable: false },
HighestTerPlan: { type: "string", editable: false },
Max_DOS_Aging_Group: { type: "string", editable: false },
Reviewed: { type: "boolean", editable: true },
Collector_Name: { type: "string", editable: false}
}
}
},
transport: {
read: {
url: "/api/SelfPayData/Get", // <-- Get data from here
dataType: "json" // <-- The default was "jsonp"
},
update: {
url: "/api/SelfPayData/PUT",
dataType: "json", // <-- The default was "jsonp"
contentType: "application/json; charset=utf-8",
type: "PUT"
},
parameterMap: function (data, operation) {
if (operation != "read") {
return JSON.stringify(data.models);
} else {
var paramMap = kendo.data.transports.odata.parameterMap(data);
var orderBy = paramMap.$orderby;
if (orderBy == undefined) {
orderBy = "account__";
}else {
orderBy = orderBy + ",account__";
}
paramMap.$orderby = orderBy;
var filter = paramMap.$filter;
if (filter == null || filter == '') {
delete paramMap.$filter;
}
delete paramMap.$format; // <-- remove format parameter.
return paramMap;
}
}
}
});
$(function () {
$("#grid").kendoGrid({
sortable: true,
pageable: true,
scrollable: true,
resizable: true,
editable: true,
navigatable: true,
filterable: {
extra: false,
operators: {
string: {
startswith: "Starts with",
eq: "Is equal to",
neq: "Is not equal to"
}
}
},
columns: [
{
field: "cstsv_resolved",
title: "Cstsv Resolved",
width: "5em",
filterable: true
},
{
field: "cstsv_rep",
title: "Cstsv Rep",
width: "8em",
filterable: true
},
{
field: "cstsv_comp_date",
title: "Cstsv Comp Date",
width: "6em",
filterable: true
},
{
field: "region",
title: "Region",
width: "5em",
filterable: true
},
{
field: "db",
title: "DB",
width: "4em",
filterable: true
},
{
field: "personid",
title: "Person ID",
width: "6em",
filterable: true
},
{
field: "legacyid",
title: "Legacy ID",
width: "6em",
filterable: true
},
{
field: "account__",
title: "Account #",
width: "6em",
filterable: true
},
{
field: "deceased",
title: "Deceased",
width: "5.2em",
filterable: true
},
{
field: "patient_name",
title: "Patient Name",
width: "6em",
filterable: true
},
{
field: "account_balance",
title: "Account Balance",
width: "5em",
filterable: true,
format: "{0:c2}"
},
{
field: "pat_last_paid_date",
title: "Pat Last Paid Date",
width: "6em",
format: "{0: MM-dd-yyyy}",
filterable: true
},
{
field: "pat_last_paid_amt",
title: "Pat Last Paid Amt",
width: "6em",
filterable: true,
format: "{0:c2}"
},
{
field: "acct_stat",
title: "Acct Stat",
width: "5em",
filterable: true
},
{
field: "bill_type",
title: "Bill Type",
width: "5em",
filterable: true
},
{
field: "acct_score",
title: "Acct Score",
width: "4em",
filterable: true
},
{
field: "tu_status",
title: "TU Status",
width: "6em",
filterable: true
},
{
field: "scoring",
title: "Scoring",
width: "4em",
filterable: true
},
{
field: "coll_ltr",
title: "Coll Ltr",
width: "5em",
filterable: true
},
{
field: "HighestPriPlan",
title: "Pri Plan",
width: "5em",
filterable: true
},
{
field: "HighestSecPlan",
title: "Sec Plan",
width: "5em",
filterable: true
},
{
field: "HighestTerPlan",
title: "Ter Plan",
width: "5em",
filterable: true
},
{
field: "Max_DOS_Aging_Group",
title: "DOS Aging Group",
width: "5em",
filterable: true
},
{
field: "Reviewed",
title: "Reviewed",
width: "10em",
filterable: true
},
{
field: "Collector_Name",
title: "Collector Name",
width: "10em",
filterable: true
}
],
dataSource: selfPayDataSource
});
});
The models field is available only when the batch option is set to true. This doesn't seem to be the case here. The model fields are exposed in the data parameter when batch is set to false.

After I click on the Update button in Kendo Grid, the insert into the database works but this doesnt cause the grid to exit edit mode

Below is my grid.
If you look at the save: event, you'll notice an AJAX call.
This AJAX call IS firing, data IS being inserted into the database and I can even see the alert function going through. However, the grid does not exit edit mode for the row I'm inline editing. I'm not sure what's going on because the error message is terrible. I keep getting:
TypeError: Cannot read property 'data' of undefined [http://localhost/x/Scripts/kendo.web.min.js:13]
Here's the grid:
function directorsOrRecipients(e)
{
awardTitleId = e.data.AwardTitleId;
var detailRow = e.detailRow;
detailRow.find(".childTabstrip").kendoTabStrip({
animation: {
open: { effects: "fadeIn" }
}
});
detailRow.find(".directorsOrRecipients").kendoGrid({
reorderable: true,
resizable: true,
dataSource: {
transport: {
read: {
url: "http://localhost/x/api/Awards/directors/" + awardTitleId,
type: "GET"
},
},
schema: {
model: {
id: "AwardDirectorId",
fields: {
"AwardDirectorId": { editable: false, type: "number" },
"namefirstlast": { editable: true, type: "string" },
"directorsequence": { editable: true, type: "number", validation: { min: 1 } },
"isonballot": { editable: true, type: "string" },
"concatenation": { editable: true, type: "string" },
"MoreNames": { editable: true, type: "number", validation: { min: 0 } },
}
}
}
},
columns: [
{ field: "AwardDirectorId", title: "Award Director Id" },
{ field: "namefirstlast", title: "Name", editor: namesAutoComplete },
{ field: "directorsequence", title: "Director Sequence", format: "{0:n0}" },
{ field: "isonballot", title: "On ballot?", editor: onBallotDropDownEditor },
{ field: "concatenation", title: "Concatenation" },
{ field: "MoreNames", title: "More names?", format: "{0:n0}" },
{ command: ["edit"], title: " ", width: 100 }],
sortable: true,
sort: { field: "namefirstlast", dir: "desc" },
editable: "inline",
toolbar: [{ name: "create", text: "Add New Director/Recipient" }],
save: function(e)
{
debugger;
if (e.data != "undefined")
{
$.ajax({
url: "http://localhost/x/api/awards/directors",
type: "POST",
dataType: "json",
data: $.parseJSON(directorData)
}).done(function()
{
alert('done!');
});
}
}
});
function onBallotDropDownEditor(container, options)
{
var data = [
{ "onBallotId": 1, "onBallotDescription": "Yes" },
{ "onBallotId": 2, "onBallotDescription": "No" }];
$('<input required data-text-field="onBallotDescription" data-value-field="onBallotDescription" data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList({
autoBind: false,
dataSource: data
});
}
}
After Success in Ajax call try this,
$('#GridName').data('kendoGrid').dataSource.read();
$('#GridName').data('kendoGrid').refresh();
In controller update function return an object insted of empty Json, like this it worked for me
return Json(ModelState.IsValid ? new object() : ModelState.ToDataSourceResult());

Resources