Kendoui grid, datasource and restful service - kendo-ui

Q1: I'm trying to get the kendoui grid bound to a datasource talking to a restful service, (using servicestack). All is working ok except when I call PUT and the rest service sends back the persisted poco object I get a strange javascript error and you do not get to the success method of the datasource.
Error is
Uncaught SyntaxError: Unexpected number kendo.all.min.js:9
extend.setter kendo.all.min.js:9
o.extend._set kendo.all.min.js:9
T.extend.accept kendo.all.min.js:9
o.extend._accept kendo.all.min.js:9
(anonymous function) kendo.all.min.js:9
n jquery.min.js:2
o.fireWith jquery.min.js:2
o.fire jquery.min.js:2
g.(anonymous function).call.c.success kendo.all.min.js:9
n jquery.min.js:2
o.fireWith jquery.min.js:2
w jquery.min.js:4
d
The datasource/grid configuration looks like
$(document).ready(function () {
var crudServiceBaseUrl = "/api/configuration/databaseconnections";
$("#grid").kendoGrid({
dataSource: {
type: "json",
transport: {
read: {
url: crudServiceBaseUrl,
dataType: "json"
},
update: {
url: function (db) {
console.log(db);
return crudServiceBaseUrl + "/" + db.Id;
},
type: "PUT",
success: function (result) {
console.log(result);
}
//dataType: "json"
},
destroy: {
url: function (db) {
return crudServiceBaseUrl + "/" + db.Id;
},
type: "DELETE",
//dataType: "json"
},
create: {
url: function (db) {
return crudServiceBaseUrl + "/" + db.Id;
},
type: "PUT",
//dataType: "json"
},
},
schema: {
model: {
id: "Id",
fields: {
Id: { type: "string" },
ConnectionString: { type: "string" },
DatabaseType: { type: "string" },
ProfileConnection: { type: "string" },
}
}
},
pageSize: 10,
serverPaging: false,
serverFiltering: false,
serverSorting: false,
model: {
id: "Id",
fields: {
ConnectionString: { editable: true },
DatabaseType: { editable: false, nullable: false, validation: { required: true } },
ProfileConnection: { editable: false, nullable: false, validation: { required: true } },
}
}
},
height: 250,
filterable: true,
sortable: true,
pageable: true,
reorderable: true,
resizable: true,
toolbar: ["create"],
columns: [{
field: "Id",
filterable: false,
width: 150,
},
{
field: "ConnectionString",
title: "Connection String",
filterable: false,
}, {
field: "DatabaseType",
title: "Type",
width: 100
},
{
field: "ProfileConnection",
title: "Profile",
width: 100
},
{ command: ["edit", "destroy"], title: " ", width: "210px" }
],
editable: "popup"
});
});
Q2: Anyone have an idea or a sample of the kendoui datasource working with a crud rest service ?

Q1: As you mentioned in your comment you found the problem.( ";" in connection string)
Q2: But for second question, download and check this sample code (Binding grid to a Web ApiController) it may help you or others refer here.

Related

Kendo Datasource updating remote data

What am I doing wrong? I have a kendo datasource setup as such
var sharedDataSource = new kendo.data.DataSource({
transport: {
read:
{
url: "/Home/ReadStarkArea",
dataType: "json"
},
update:
{
url: "/Home/UpdateStarkArea",
dataType: "json"
},
destroy:
{
url: "/Home/DeleteStarkArea/",
dataType: "json"
},
schema: {
model: {
id: "Id",
fields: {
id: { type: "number", editable: false },
ZipCode: { type: "string" },
CarrierRoute: { type: "string" }
}
}
}
}
});
$("#grid").kendoGrid({
dataSource: sharedDataSource,
autoBind: true,
selectable: true,
toolbar: ["create"],
columns: [
{ field: "ZipCode", title: "Zipcode" },
{ field: "CarrierRoute", title: "Carrier Route" },
{ command: ["edit", "destroy"], title: " " }],
editable: "popup"
});
the URL's defined in the transport all point to methods in my controller. The read works fine but neither the update or destroy call the their methods. Furthermore, once I get the update and delete calling the correct methods, how do I know what data needs updating? does the transport pass a param with the changes?

Giving a unique ID on create new row for the kendo grid in the JS

I have a kendo grid.. It works fine.. But when I create a new row in the grid I need to provide a unique ID (integer is fine but not a duplicate one eg. 0, 1, 2, 3.. ) to save. At the moment when I get data from backend I count the number of rows and keep it in the session. And when an user requests for new row, I read the session and find the number of rows there and add 1 to create a unique ID. Is there any elegant way of giving a unique ID for the grid in the JS without using the session. Thanks in advance.
$("#TrainingDetailsGrid").kendoGrid({
dataSource: {
transport: {
read: {
url: "GetTrainingDetailsData",
datatype: "json",
type: "POST",
contentType: "application/json"
},
create: {
url: "UpdateTrainingDetailsData",
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json"
},
update: {
url: "UpdateTrainingDetailsData",
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json"
},
parameterMap: function (data, operation) {
if (operation != "read") {
return kendo.stringify(data.models);
}
}
},
pageSize: 5,
serverPaging: false,
batch: true,
schema: {
model: {
id: "ID",
fields: {
ID: { editable: false },
Description: { editable: true, nullable: false, validation: { required: true } },
Instructor: { editable: true, nullable: false, validation: { required: { message: "Instructor name is required" } } },
Trainee: { editable: true },
TimeSpent: { editable: true, type: "number", validation: { required: { message: "Hours are required" }, min: 0, step: 0.25 } },
}
},
errors: "Errors"
},
error: function (e) {
alert(e.errors + "TrainingDetailsGrid");
}
},
groupable: false,
autoBind: false,
sortable: true,
toolbar: ["create"],
editable: "inline",
pageable: {
refresh: true,
pageSizes: true
},
dataBound: onDataBound,
columns:
[
{ field: "Description", width: 90, title: "Description" },
{ field: "Instructor", width: 90, title: "Instructor" },
{ field: "Trainee", width: 90, title: "Trainee" },
{ field: "TimeSpent", width: 90, title: "Hours" },
{ command: ["edit"], title: "Action", width: "175px" }
]
});
In your parameterMap you can count the number of rows you have in the Grid and put the value in the model before you pass it to the server side.
parameterMap: function (data, operation)
{
if (operation != "read") {
if (operation == "create") {
if ($("#TrainingDetailsGrid").data("kendoGrid").dataSource.total() > 0) {
data.models[0].ID = $("#TrainingDetailsGrid").data("kendoGrid").dataSource.total() - 1;
}
else {
data.models[0].ID = 0;
}
}
return kendo.stringify(data.models);
}
}

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());

Kendo UI DataSource not triggering transport.destroy

I am using Kendo UI with ASP.NET Web API. There is a ProjectsController that has all the necessary methods.
My issue is that when I click on Delete button, Kendo UI grid will raise remove() event, but DataSource never invokes transport.destroy. Rather, it seems that tansport.create is being invoked. In transport.parameterMap I can see that the operation is create instead of destroy.
Here is a sample JavaScript code:
$(document).ready(function () {
var apiUrl = '/api/projects/';
var dataType = 'json';
var dataSource = new kendo.data.DataSource({
batch: true,
autoSync: false,
transport: {
read: {
url: apiUrl,
dataType: dataType,
type: "GET"
},
update: {
url: apiUrl,
dataType: dataType,
type: "PUT"
},
destroy: {
url: apiUrl,
type: "DELETE"
},
create: {
url: apiUrl,
contentType: "application/json;charset=utf-8",
dataType: dataType,
type: "POST"
},
parameterMap: function (data, operation) {
console.log("Operation: " + operation);
if (operation === "create" && data.models) {
for (var i in data.models) {
var model = data.models[i];
if (model.ProjectId === 0) {
return kendo.stringify(model);
}
}
} else if (operation === "destroy") {
console.log("Data.Models: " + data.models);
console.log("Data.id: " + data.ProjectId);
return { id: data.ProjectId };
}
return data;
}
},
schema: {
id: "ProjectId",
model: {
fields: {
ProjectId: { type: "number", editable: false, nullable: false, defaultValue: 0 },
ProjectName: { type: "string", validation: { required: true } },
Status: { type: "string", validation: { required: true } },
IsActive: { type: "boolean" }
}
}
},
pageSize: 10,
serverPaging: false,
serverFiltering: false,
serverSorting: false
});
$("#projectsGrid").kendoGrid({
dataSource: dataSource,
groupable: false,
sortable: true,
pageable: {
refresh: true,
pageSizes: true
},
pageSize: 10,
toolbar: ["create"],
editable: "popup",
columns: [
{ field: "ProjectId", width: 30, title: "ID" },
{ field: "ProjectName", width: 180, title: "Project" },
{ field: "Status", width: 90, title: "Status" },
{ field: "IsActive", width: 40, title: "Is Active", type: "boolean", template: '<input type="checkbox" #if (IsActive) {# checked="checked" #}# disabled="disabled" />' },
{ command: ["edit", "destroy"], title: "&nbsp", width: "80px" }
],
remove: function (e) {
console.log("Delete button clicked.");
console.log("Project ID: " + e.model.ProjectId);
//dataSource.remove(e.model);
//dataSource.sync();
}
});
});
Web API works fine when requests are issued via Fiddler, but Kendo UI Grid shows:
POST http://localhost:port/api/Projects
when it should be DELETE.
Thanks everyone in advance!
On your datasource, you have the batch flag set to true, this means the datasource will make the call only after you tell it to, e.g calling sync().
http://docs.kendoui.com/api/framework/datasource#configuration-batch
As well as
Make sure you have defined Id in the model, as OnaBai explained here Why does the KendoUI Grid Transport Create event gets raised multiple times, and even when the action is Update? , your id is outside the model, should be in :
model: {
id: "ProductID",
fields: {
ProductID: { editable: false, nullable: true },
}
}
if someone has defined the id in model as answered in above ,but dataSource not triggering transport.destroy yet ,below configuration could be helpful:
editable: {
..
mode: "inline", //or "popup
...
}
//or
editable: "inline" //or "popup"
http://www.telerik.com/forums/transport-destroy-of-grid-editor-is-not-working

Kendo grid post and delete send null to controller

I'm posting a kendoui web grid and it isn't sending data and I can't see what I'm doing different from the sample that's failing. I'm posting to the controller, but it's either empty (if batch: true or null if batch: false)
var crudServiceBaseUrl = "api/Certifications/",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + member.id,
dataType: "json"
},
update: {
url: crudServiceBaseUrl,
type: "Post",
dataType: "json"
},
destroy: {
url: crudServiceBaseUrl,
type: "Delete",
contentType: "application/json; charset=utf-8",
dataType: "json"
},
create: {
url: crudServiceBaseUrl,
type: "Post",
dataType: "json"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
},
editable: { //disables the deletion functionality
update: true,
destroy: true
},
batch: true,
pageSize: 30,
schema: {
model: {
id: "Id",
fields: {
Id: { editable: false, nullable: true },
MemberId: { editable: false, nullable: true },
Name: { validation: { required: true} },
AuthorityName: { validation: { required: true} },
StartDate: { type: "date", validation: { required: true} },
EndDate: { type: "date" }
}
}
}
});
$("#certifications").kendoGrid({
dataSource: dataSource,
pageable: true,
height: 300,
toolbar: ["create"],
columns: [
{ field: "Name", title: "Product Name", width: 250 },
{ field: "AuthorityName", title: "Authority", format: "{0:c}", width: "140px" },
{ field: "StartDate", title: "Earned", template: '#= kendo.toString(StartDate,"MM/dd/yyyy") #', width: 50 },
{ field: "EndDate", title: "Expired", template: '#= kendo.toString(EndDate,"MM/dd/yyyy") #', width: 50 },
{ command: ["edit", "destroy"], title: " ", width: "130px" }],
editable: "popup"
});
the web api:
public Certification DeleteCertification(CertificationVm cert)
{
var model = Uow.Certifications.Get(cert.Id);
if (model == null)
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NoContent));
Uow.Certifications.Delete(model);
Uow.Commit();
return model;
}
I'd figured it out, although I had to depart from the example http://demos.kendoui.com/web/grid/editing-popup.html
The fix was add the content type, correctly use dataType: "json" as noted above, change from batch: true to batch: false and change the parameter map to the below
destroy: {
url: crudServiceBaseUrl,
type: "Delete",
contentType: "application/json; charset=utf-8",
dataType: "json"
},
parameterMap: function (model, operation) {
if (operation !== "read" && model) {
return kendo.stringify(model) ;
}
}
There is no such thing as jsonp + POST - it is discussed here.
Do not use jsonp unless you really know why you need it.

Resources