Kendo Grid calls 'create' operation instead of 'update' after adding new record - kendo-ui

I've setup a basic Kendo Grid and I'm using the DataSourceResult class from the PHP Wrapper library on the sever side.
I've come across a strange issue... if I create a new record and then edit it (without refreshing the page), the create operation is called again, rather than the update operation.
If the page is refreshed after adding the new record, the update operation is called correctly after making changes to the record.
I can confirm that the DataSourceResult class is returning the correct data after the create operation, including the id of the new record.
Any ideas why this is happening (and how to stop it)?
Thanks
Update: Here's the datasource code. The query string in the url is just to easily distinguish the requests in Chrome's console. The additional data passed with each request is used by ajax.php to distinguish the different actions requested.
data = new kendo.data.DataSource({
transport: {
create: {
url: '/ajax.php?r=gridCreate',
dataType: 'json',
type: 'post',
data: { request: 'grid', type: 'create' }
},
read: {
url: '/ajax.php?request=gridRead',
dataType: 'json',
type: 'post',
data: { request: 'grid', type: 'read' }
},
update: {
url: '/ajax.php?r=gridUpdate',
dataType: 'json',
type: 'post',
data: { request: 'grid', type: 'update' }
},
destroy: {
url: '/ajax.php?r=gridDestroy',
dataType: 'json',
type: 'post',
data: { request: 'grid', type: 'destroy' }
},
parameterMap: function(data, operation) {
if (operation != "read"){
data.expires = moment(data.expires).format('YYYY-MM-DD HH:mm');
}
return data;
}
},
schema: {
data: 'data',
total: 'total',
model: {
id: 'id',
fields: {
id: { editable: false, nullable: true },
code: { type: 'string' },
expires: { type: 'date' },
enabled: { type: 'boolean', defaultValue: true }
}
}
},
pageSize: 30,
serverPaging: true,
serverSorting: true,
serverFiltering: true
});

Best solution
Set to update, create or delete different Call Action
From Telerik Support :
I already replied to your question in the support thread that you
submitted on the same subject. For convenience I will paste my reply
on the forum as well.
This problem occurs because your model does not have an ID. The model
ID is essential for editing functionality and should not be ommited -
each dataSource records should have unique ID, records with empty ID
field are considered as new and are submitted through the "create"
transport.
schema: {
model: {
//id? model must have an unique ID field
fields: {
FirstName: { editable: false},
DOB: { type: "date"},
Created: {type: "date" },
Updated: {type: "date" },
}
} },
For more information on the subject, please check the following
resources:
http://docs.kendoui.com/api/framework/model#methods-Model.define
http://www.kendoui.com/forums/ui/grid/request-for-support-on-editable-grid.aspx#228oGIheFkGD4v0SkV8Fzw
MasterLink
I hope this information will help

I have also the same problem & I have tried this & it will work.
.Events(events => events.RequestEnd("onRequestEnd"))
And in this function use belowe:
function onRequestEnd(e) {
var tmp = e.type;
if (tmp == "create") {
//RequestEnd event handler code
alert("Created succesully");
var dataSource = this;
dataSource.read();
}
else if (tmp == "update") {
alert("Updated succesully");
}
}
Try to Use this code in onRequestEnd event of grid
var dataSource = this;
dataSource.read();
Hope that it will help you.

Pass the auto-incremented id of the table when you call the get_data() method to display data into kendo grid, so that when you click on the delete button then Deledata() will call definitely.

Another variation, in my case, I had specified a defaultValue on my key field:
schema: $.extend(true, {}, kendo.data.transports["aspnetmvc-ajax"], {
data: "Data",
total: "Total",
errors: "Errors",
model: kendo.data.Model.define({
id: "AchScheduleID",
fields: {
AchScheduleID: { type: "number", editable: true, defaultValue: 2 },
LineOfBusinessID: { type: "number", editable: true },
Not sure what I was thinking but it caused the same symptom.

Related

Kendo DropDownList Not Binding Data

I am using a Kendo dropdownlist to display data made from a remote service call.
First, here is the definition in the HTML template:
<select
kendo-drop-down-list
k-options="dropdownOptions"
k-ng-delay="dropdownOptions">
</select>
Next, here is the code to populate the dropdown from an AngularJS controller:
var myUrl = '(url of REST service)';
$scope.dropdownOptions = {
dataSource: {
transport: {
read: {
url: myUrl,
dataType: 'json',
type: 'POST',
contentType: "application/json;charset=ISO-8859-1"
},
parameterMap: function (data, type) {
const req = {
"PARAMS": $scope.params
};
return JSON.stringify(req);
}
}
},
dataTextField: 'DESCRIPTION',
dataValueField: 'VALUE',
schema: {
type: "json",
data: "resultData",
model: {
id: "VALUE",
fields: {
"VALUE":{field: "VALUE", type: "string"},
"DESCRIPTION":{field: "DESCRIPTION", type: "string"}
}
}
}
};
(Note: the REST service requires data to be provided as a JSON object via POST, hence the type and parameterMap).
I have confirmed that the data to populate the dropdown is being returned from the REST service as an array under the key "resultData":
{
"resultData":[{"DESCRIPTION":"Whatever","VALUE":"VALUE1"},...]
}
Can anyone help me?
Update
I am also seeing "e.slice is not a function" in my dev console.
Edit
Added id field to model, no effect.
The problem was that schema should have been a child of dataSource. Once I fixed that, the data began to display.

Kendo Grid does not update the grid with newly created id after creation

I am trying to build a very simple Kendo CRUD grid with a table that has only two columns: ID and Name. I have configured the grid with serverside pagination and serverside filtering.
Everything seems to function as expected but after the new record is created, the grid shows the new record but without the ID field. On creation, the request has ID null but I am sending the value of id and the full object after creation. In example grids, the grid is updated with new values. What do I need to change / add to ensure that the ID of the newly created record shows up in Grid as well?
Following is the JSP:
<script>
$(function() {
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url:"http://localhost:8181/baseweb/countrylist",
dataType: "jsonp"
},
update: {
url: "http://localhost:8181/baseweb/countryupdate",
dataType: "jsonp"
},
destroy: {
url: "http://localhost:8181/baseweb/countrydelete",
dataType: "jsonp"
},
create: {
url: "http://localhost:8181/baseweb/countrycreate",
dataType: "jsonp"
},
parameterMap: function(data, operation) {
if (operation !== "read" && data.models) {
return {grid_options: kendo.stringify(data.models)};
}
return {grid_options: kendo.stringify(data)};
}
},
serverPaging: true,
serverFiltering: true,
pageSize: 10,
schema: {
data: "data",
total: "total",
model: {
id: "id",
fields: {
id: { editable: false, nullable: true },
name: { validation: { required: true } }
}
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
pageable: true,
filterable: true,
height: 400,
toolbar: ["create"],
columns: [
{ field: "id", title:"Identification"},
{ field: "name", title:"Country Name" },
{ command: ["edit", "destroy"], title: " ", width: "160px" }
],
editable: "popup"
});
});
</script>
Parameter Sent to the server on create:
_ 1380846899054
callback jQuery19108827040256333442_1380846899052
grid_options {"id":null,"name":"testing"}
Parameter sent back from server as response:
jQuery19108827040256333442_1380846899052([ {"id":"4028828f4180d64a014180e3bda20002","name":"testing"}])
I am expecting that the ID sent back by server should be displayed in the Grid. I have searched this forum, Kendo documentation and Google for an answer but I am unable to find a solution.
What am I missing?
Update with Solution:
Jack's answer provided the clue to finding the solution. I was making two mistakes:
a. The callback in Kendo Grid seems to expect the data back in a "data:" attribute. I was not naming the result set as "data:" in my response.
b. The callback also expects a JSONArray of objects in the data: attribute. I was sending a JSONObject since I was only creating one object.
After I changed the response to include data: attribute and JSONArray, it works perfectly.
The request parameter from the client looks like this:
_ 1386350196768
callback jQuery19101285024500179227_1386350196765
grid_options {"id":null,"name":"Ghana"}
The edited response looks like this:
jQuery19101285024500179227_1386350196765( {"data":[{"id":"2c9323ca42c8df630142c944450b0002","name":"Ghana"}]})
Hope it helps someone else as this is not clearly documented in the official documentation.
There is a nice clean way of doing this...
If your grid is created in script block:
dataSource: {
transport: {
read: {
url: "..."
},
create: {
url: "...",
type: "POST",
complete: function(e) {
$("#grid").data("kendoGrid").dataSource.read();
}
},
}...
OR in HTML
#(Html.Kendo().Grid<ViewModel>()
.Name("grid")
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(10)
.Model(model =>
{
model.Id(i => i.Cde);
model.Field(i => i.Description).Editable(true);
})
.Read(read => read.Action("EditingInline_Read", "UserGroups"))
.Update(update => update.Action("EditingInline_Update", "UserGroups")).Read("EditingInline_Read", "UserGroups")
.Destroy(delete => delete.Action("EditingInline_Delete", "UserGroups"))
.Create(create => create.Action("EditingInline_Create", "UserGroups")).Read("EditingInline_Read", "UserGroups")
)
.Columns(columns =>
{
columns.Bound(s => s.Decription);
columns.Bound(s => s.enabled);
columns.Command(command => { command.Edit(); command.Destroy(); }).Width(200);
})
.Pageable()
.Sortable()
.Selectable(selectable => selectable
.Mode(GridSelectionMode.Single))
.ToolBar(toolbar => toolbar.Create()))
Check out the CRUD calls, more specific, Update and Create.
I've had the same problem and think I may have found the answer. If in the schema you define the object that holds the results, you must return the result of the created link in that same object. Example:
schema: {
data: "data",
total: "total", ....
}
Example MVC method:
public JsonResult CreateNewRow(RowModel rowModel)
{
// rowModel.id will be defaulted to 0
// save row to server and get new id back
var newId = SaveRowToServer(rowModel);
// set new id to model
rowModel.id = newId;
return Json(new {data= new[] {rowModel}});
}

Kendo UI does not call create if a function is specified

Using Kendo.web.js versions 2013.2.716 and 2012.3.1315, I am trying to use a function in my transport.create rather than calling a URL. What I find is that the function does not get called. Instead a default URL is called and the resulting HTML appears to cause an error in the bowels of kendo because it is expected to be JSON instead.
I assume that this is some type of configuration error, but I can't figure out where the problem is.
Here is a snippet of the code:
var clientListDS = new kendo.data.DataSource({
transport: {
read: {
url: window.baseUrl + 'HealthCheck/ClientSummary',
dataType: 'json',
type: 'POST'
},
create: function(a,b,c) { alert('Create'); },
createY: window.baseUrl + 'HealthCheck/DontCallMe',
createX: {
url: window.baseUrl + 'HealthCheck/DontCallMe',
dataType: 'json',
type: 'POST'
},
whatWeWantCreateToDo: function () {
showChooseDialog('Some Random String', 'Select Client', OnRefreshInactiveClientList);
},
destroy: function () {
alert('destroy');
},
update: function () {
alert('update');
}
},
autoSync: true,
schema: {
model: {
id: 'ID',
fields: {
ID: { required: false, type: 'number', nullable: true },
ClientName: { type: 'string' },
ClientTag: { type: 'string' },
Status: { type: 'string' }
}
}
}
});
Then I use the resulting data source to build a grid like this:
$('#cClientGrid').kendoGrid({
dataSource: clientListDS,
columns: [
{ field: 'ClientTag', title: 'Tag'},
{ field: 'ClientName', title: 'Name' },
{ field: 'Status' }
],
editable: {
mode: 'incell',
createAt: 'bottom'
},
edit: function (pEvent) {
if (pEvent.model.isNew())
alert('create');
else
alert('Edit');
},
toolbar: ['create']
});
Some behavior that is worthy of note:
You see several attempts at the create configuration. If I use CreateY or CreateX, it will call the resulting URL. If I use Create or WhatWeWantCreateToDo, I end up downloading the containing page with each element of my schema as get string items (I assume this is some type of default behavior as I can't find a reference to the URL which is downloaded).
When I turn off autoSync, the grid will call its edit function when I use the toolbar to create a new item. When I turn on autoSync, the edit function does not get called. Instead the data source create functionality runs.
Any thoughts or insight on how I might be able to call a function instead of a URL will be appreciated.
First make in transport everything being an URL or a function, do not mix them up.
If you need to implement read as a function, you simply do:
transport: {
read : function (options) {
$.ajax({
url: window.baseUrl + 'HealthCheck/ClientSummary',
dataType: 'json',
type: 'POST',
success : function (result) {
options.success(result);
}
});
},

kendo grid delete command not working

i have developed a web application using kendo ui tools and theres a kendo grid with batch edit mode..
but when i press the delete button for any record in kendo grid it will erase from the list in grid but actually not in the data source.when i reload the page or grid the deleted item will still exist..
here is the code of my grid
<div id="grid">
</div>
<script type="text/javascript">
$("#submitMarketUser").click(function () {
var grid = $("#grid").data("kendoGrid");
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "WholeSaleTrade/GetTradeProductDetail",
dataType: "json",
data: {
test: $("#Names").val()
}
},
destroy: {
url: "WholeSaleTrade/DeletePro",
type: "POST",
dataType: "jsonp",
data: {
DAKy: $("#Names").val(),
DIKy: $("#btntxt").val()
}
},
create: {
url: "WholeSaleTrade/CreateProduct",
type: "POST",
dataType: "jsonp",
data: {
AKy: $("#Names").val(),
IKy: $("#btntxt").val()
}
}
},
pageSize: 5,
schema: {
model: {
id: "ProductKey",
fields: {
ProductKey: { editable: false, nullable: true },
ProductName: { validation: { required: true} }
}
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
editable: true,
toolbar: ["create", "save"],
autobind: true,
pageable: true,
columns: [
{ field: "ProductName", title: "Product Name",
editor: function (container, options) {
var model = options.model;
$('<input id="btntxt" name="' + options.field + '"/>').appendTo(container).kendoComboBox({
dataSource: {
type: "POST",
transport: {
read: {
url: "MarketInformation/PopulateProducts",
success: function (data) {
var prod = data[0];
model.set("ProductName", prod.ItmNm);
model.set("ItmKy", prod.ItmKy);
model.set("UserKey", $("#Names").val());
}
}
}
},
dataValueField: "ItmKy",
dataTextField: "ItmNm"
});
}
},
{ command: ["destroy"], title: " " }
]
});
});
</script>
can not identify that where is the fault going and can somebody please help me to solve this matter.
There are three common reasons delete won't work:
1. Not setting editable of grid to inline or popup. The deleted items will be automatically processed through transport destroy only for "inline"/"popup" edit modes. Ex:
editable: {
mode: "inline",
}
//or
editable: "inline"
2. If 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(). Ex:
var dataSource = new kendo.data.DataSource({
batch: true,
//.....
});
//... in some where e.g in a save button click event call the following line:
dataSource.sync();
3. You should define id to your primary key of database field name inside model of datasource. Ex:
model: {
id: "ProductID",
fields: {
ProductID: { editable: false, nullable: true },
}
}
So the problem with your code is first one, i.e you did not set editable to inline or popup
If you choose not to include editable.mode in order to utilize the in-cell editing, you can set the toolbar of the grid to include the option save:
$("#grid").kendoGrid({
dataSource: {
transport: {
....
},
schema: {
....
}
},
toolbar: ["create", "save", "cancel"],
columns: [
....
],
editable: true
});
This will create a save button at the toolbar of the grid. After deleting any records by clicking the destroy command button, click on the save button to have the grid to make an Ajax call to the server to delete the record.
If you would rather delete the record automatically without including the save button, you could add a change event handler to the datasource of the grid:
$("#grid").kendoGrid({
dataSource: {
transport: {
....
},
schema: {
....
},
change: function(e) {
if (e.action === "remove") {
this.sync();
}
}
},
columns: [
....
],
editable: true
});
This will automatically sync the changes you made to the grid with the server when there's a data change.
Hmm try not including type: "POST", and see if it now works since as far as I can see that bit isn't included on the demo's and I don't think I included it when I last did inline edits/deletes.
I had put an arbitray name for an int on the server Delete Method.
[HttpPost]
public ActionResult DeleteRandomTest(Int32 randomTestId)
{
...
}
The default modelbinder was probably looking for a property called Id (same as the primary key of my type according to the configuration of the model).
.Model(config => config.Id(p => p.Id))
In fact, I proved this by changing the signature to the following:
[HttpPost]
public ActionResult DeleteRandomTest(Int32 Id)
{
...
}
My break point was hit after that.
Ultimately, I used the full type as the parameter as shown in the Kendo examples because I didn't want to have poorly named parameter names (not camel case) in the action. Shown as follows:
[HttpPost]
public ActionResult DeleteRandomTest([DataSourceRequest]
DataSourceRequest request, RandomDrugTest randomDrugTest)
{
...
}
This seems to the be the reason it wasn't working.
I had the same issue. My issue was caused by having a data property in the kendo model. Example:
{id: 1, data: ""}

kendoGrid 2013.1.319 CRUD general issue using OData through ASP.NET MVC 4 web api controller

Since I've tryed to write on kendoui forum but the answer I've got was "buy a license" for report a bug, I'm asking if someone has faced the same problem using kendoGrid 2013.1.319. Since I'm using it in a "sundays test application" there's no hurry at all!
My original message was on kendo forum was:
Hi there,
I've been updated kendo grid with the latest version and all of a sudden my application is facing problems on data operations. The problem seems to be located client side, because I'm correctly receiving requests for GET, PUT, POST and DELETE verbs but the grid does not update its status.
I'm using ASP.NET MVC 4 OData implementation through an API service.
For example: if I delete 2 rows and press save, the DELETE calls are made, the client grid hides the rows but if I press save again, the delete is called on and on.
The same problem is on update / create, the cell remains with the red corner and, after saving, again the data are still submitted as it was the first time.
I've noticed that when I receiving the callback on dataSource:
requestEnd: function (e) {
if (e.type === "update" || e.type === "create") {
// Refresh data after changes
this.read();
}
}
e.type is always undefined when inserting or updating records.
This is my dataSource configuration:
dataSource: {
type: 'odata', // <-- Include OData style params on query string
transport: {
read: {
url: $("#contactsGrid").attr("data-api-crud"),
dataType: "json", // <-- The default is "jsonp".
type: "GET"
},
update: {
url: $("#contactsGrid").attr("data-api-crud"),
dataType: "json", // <-- The default is "jsonp".
type: "POST"
},
create: {
url: $("#contactsGrid").attr("data-api-crud"),
dataType: "json", // <-- The default is "jsonp".
type: "PUT"
},
destroy: {
url: function (data) {
return $("#contactsGrid").attr("data-api-crud") + "/" + data.Id;
},
dataType: "json", // <-- The default is "jsonp".
type: "DELETE"
},
parameterMap: kendo.data.transports.odata.parameterMap
},
schema: {
// The array of repeating data elements (items)
data: "Results",
// The total count of records in the whole dataset. used for paging.
total: "Count",
model: {
id: "Id",
fields: {
Dealer: { type: "string", editable: true },
Address: { type: "string", editable: true }
}
}
},
pageSize: 50,
serverPaging: true,
serverFiltering: true,
serverSorting: true,
requestEnd: function (e) {
if (e.type === "update" || e.type === "create") {
// Refresh data after changes
this.read();
}
}
}
the Kendo UI team have just published a blogpost how to use the library with JayData to simplify the configuration of datasources. Hopefully it will help you.

Resources