Kendo Grid how to datasource update,create,delete - javascript

For some reasons I cannot use MVC-wrapper of Kendo grid. So I am trying to build Kendo grid on JavaScript.
There are 2 main problems when trying to update or create records on grid.
1-)All operations(destroy,update,create) on grid just go to create action by Datasource's of Kendo grid. For example after update a record, datasource send data to this URL to many times(number of columns):
http://localhost:63186/Administrator/DefinitionDetailCreate. It should pass values to:
http://localhost:63186/Administrator/DefinitionDetailUpdate
2-)After operation(update or create) Grid sends all data to Action Method instead of new or updated data. So it sends requests the number of columns on grid
JavaScript:
var dataItem = this.dataItem($(e.target).closest("tr"));
var code = dataItem.CODE;
// alert(code);
var crudServiceBaseUrl = "/Administrator/",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: '#Url.Action("DefinitionDetailRead", "Administrator")',
data: {DefinitionCode: code},
dataType: "json"
},
update: {
url: '#Url.Action("DefinitionDetailUpdate", "Administrator")',
type: "POST",
dataType: "text"
},
destroy: {
url: '#Url.Action("DefinitionDetailDelete", "Administrator")',
type: "POST",
dataType: "text",
},
create: {
url: '#Url.Action("DefinitionDetailCreate", "Administrator")',
type: "POST",
dataType: "text",
}
},
// batch: true,
pageSize: 9,
schema: {
data: "Data",
model: {
ID: "ID",
fields: {
ID: {editable: false, nullable: true},
DESCRIPTION: {validation: {required: true}}
}
}
}
});
$("#detailsGrid").kendoGrid({
dataSource: dataSource,
attributes: {style: "padding-left: 0px; font-size: 14px"},
pageable: {refresh: false, pageSizes: false, buttonCount: 5},
toolbar: ["create"],
columns: [
{field: "DESCRIPTION", title: "DESCRIPTION", width: "200px"},
{command: ["edit", "destroy"], title: "Operasyon", width: "100px"}],
editable: "popup"
});
Controller:
[HttpPost]
public ActionResult DefinitionDetailUpdate(Guid ID,Guid REFERENCEID,string DESCRIPTION)
{
return null;
}
[HttpPost]
public ActionResult DefinitionDetailCreate(Guid ID, Guid REFERENCEID, string DESCRIPTION)
{
return null;
}

First you might need to add parameterMap, this will help identify server side methods:
parameterMap: function (options, operation) {
var out = null;
switch (operation) {
case "create":
out = '{ "param":' + options.somevalue + '}';
break;
case "read":
out = '{ "id":' + options.somevalue + '}';
break;
case "update":
out = '{ "id":' + options.somevalue + '}';
break;
case "destroy":
out = '{ "id": ' + options.somevalue + '}';
break;
}
return out;
}
I would also suggest to keep all the dataTypes as dataType: "json"
Also you seem to be missing contentType in your transports definitions :
update: {
url: _op.serviceBaseUrl + "Update",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
complete: function (jqXhr, textStatus) {
}
},

i have posted answer for the same type of question, you may have a check
or
you may Use this code
js
var dataItem = this.dataItem($(e.target).closest("tr"));
var code = dataItem.CODE;
// alert(code);
var crudServiceBaseUrl = "/Administrator/",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: '#Url.Action("DefinitionDetailRead", "Administrator")',
type: "POST",
dataType: "json"
},
update: {
url: '#Url.Action("DefinitionDetailUpdate", "Administrator")' ,
type: "POST",
dataType: "json"
},
destroy: {
url: '#Url.Action("DefinitionDetailDelete", "Administrator")',
type: "POST",
dataType: "json",
},
create: {
url: '#Url.Action("DefinitionDetailCreate", "Administrator")',
type: "POST",
dataType: "json",
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
} },
// batch: true,
pageSize: 9,
schema: {
data: "Data",
model: {
ID: "ID",
fields: {
ID: { editable: false, nullable: true },
DESCRIPTION: { validation: { required: true } }
}
}
}
});
$("#detailsGrid").kendoGrid({
dataSource: dataSource,
attributes: { style: "padding-left: 0px; font-size: 14px"},
pageable: {refresh: false, pageSizes: false, buttonCount: 5},
toolbar: ["create"],
columns: [
{field: "DESCRIPTION", title: "DESCRIPTION", width: "200px"},
{ command: ["edit", "destroy"], title: "Operasyon", width: "100px" }],
editable: "popup"
});
Controller
[HttpPost]
public ActionResult DefinitionDetailUpdate(string models)
{
//Deserialize to object
IList<UrObjectType> objName= new JavaScriptSerializer().Deserialize<IList<UrObjectType>>(models);
return Json(objName)
}
[HttpPost]
public ActionResult DefinitionDetailCreate(string models)
{
//Deserialize to object
IList<UrObjectType> objName= new JavaScriptSerializer().Deserialize<IList<UrObjectType>>(models);
return Json(objName)
}
Note that parameterMap: function() send updated data in serialize string format with name models so you should use "models" as parameter name in your action
i hope this will help you:)

Related

Kendo treelist Child node issue

whenever i cancelled the updating process from the child node,the child node just merge with root node,i don't find error in the console or i can't find anything suspicious.but after a reload,all becomes normal
$(document).ready(function () {
var windowTemplate = kendo.template($("#windowTemplate").html());
var dataSource = new kendo.data.TreeListDataSource({
transport: {
read: {
url: "officeprofiletree",
type: 'POST',
dataType: "json"
},
update: {
url: "officeprofilenametree_update",
type: 'POST',
contentType :'application/json',
dataType: "json"
},
destroy: {
url: "officeprofilenametree_destroy",
type: 'POST',
contentType :'application/json',
dataType: "json"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models)
{
return JSON.stringify(options.models);
}
}
},
batch: true,
sort: { field: "name", dir: "asc" },
schema: {
model: {
id: "officeProfileNMId",
parentId: "parentId",
fields: {
officeProfileNMId: { type:"number" },
parentId:{nullable:true,type:"number"},
mobile:{ type:"string"},
address:{type:"string"},
phone: {type:"string"},
},
}
}
});
var window = $("#window").kendoWindow({
visible:false,
title: "Are you sure you want to delete this record?",
width: "450px",
height: "60px",
}).data("kendoWindow");
var treelist = $("#treelist").kendoTreeList({
dataSource: dataSource,
pageable: true,
dataBound: function (){
var tree = this;
var trs = this.tbody.find('tr').each(function(){
var item = tree.dataItem($(this));
if( item.parentId == null) {
$(this).find('.k-button,.k-button').hide();
}
});
},
columns: [
{ field: "name", title: "Name"},
{ field: "mobile", title:"Mobile", format: "{0:c}", hidden: true },
{ field: "address", title:"Address",hidden: true },
{ field: "phone",title:"Phone" ,hidden: true },
{ command: [
{name: "edit"},
{name: "Delete",
click: function(e){
e.preventDefault();
var tr = $(e.target).closest("tr");
var data = this.dataItem(tr);
window.content(windowTemplate(data));
window.center().open();
$("#yesButton").click(function(){
treelist.dataSource.remove(data);
treelist.dataSource.sync();
window.close();
reloading();
})
$("#noButton").click(function(){
window.close();
})
}
}
]}
] ,
editable: {
mode: "popup",
},
}).data("kendoTreeList");
});
the updation and deletion works fine by the way,Here is the fiddle
https://jsfiddle.net/me09jLy7/2/
updation:
whenever i create a child to ranikannur gives me 3 children with same name in each root ranikannur,in my database there is only one child is parented by ranikannur but treelist shows it as 3 children in each parent node,the children count 3 is getting from the total ranikannurparent nodes(here tree has 3 ranikannur parent nodes)
i guess.how is this getting the 3 children?
u just try it...
$(document).ready(function () {
var windowTemplate = kendo.template($("#windowTemplate").html());
var dataSource = new kendo.data.TreeListDataSource({
transport: {
read: {
url: "officeprofiletree",
type: 'POST',
dataType: "json"
},
update: {
url: "officeprofilenametree_update",
type: 'POST',
contentType :'application/json',
dataType: "json"
},
destroy: {
url: "officeprofilenametree_destroy",
type: 'POST',
contentType :'application/json',
dataType: "json"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models)
{
return JSON.stringify(options.models);
}
}
},
batch: true,
sort: { field: "name", dir: "asc" },
schema: {
model: {
id: "officeProfileNMId",
parentId: "parentId",
fields: {
officeProfileNMId: { type:"number" },
parentId:{nullable:true,type:"number"},
mobile:{ type:"string"},
address:{type:"string"},
phone: {type:"string"},
},
}
}
});
var window = $("#window").kendoWindow({
visible:false,
title: "Are you sure you want to delete this record?",
width: "450px",
height: "60px",
}).data("kendoWindow");
var treelist = $("#treelist").kendoTreeList({
dataSource: dataSource,
pageable: true,
dataBound: function (){
var tree = this;
var trs = this.tbody.find('tr').each(function(){
var item = tree.dataItem($(this));
if( item.parentId == null) {
$(this).find('.k-button,.k-button').hide();
}
});
},
columns: [
{ field: "name", title: "Name"},
{ field: "mobile", title:"Mobile", format: "{0:c}", hidden: true },
{ field: "address", title:"Address",hidden: true },
{ field: "phone",title:"Phone" ,hidden: true },
{ command: [
{name: "edit"},
{name: "Delete",
click: function(e){
e.preventDefault();
var tr = $(e.target).closest("tr");
var data = this.dataItem(tr);
window.content(windowTemplate(data));
window.center().open();
$("#yesButton").click(function(){
treelist.dataSource.remove(data);
treelist.dataSource.sync();
window.close();
reloading();
})
$("#noButton").click(function(){
window.close();
})
}
}
]}
] ,
editable: {
mode: "popup",
},
}).data("kendoTreeList");
});

Kendo Grid multiselect checkboxes

I have a Treeview. On selecting the edit of the treenode a kendo grid for Roles will be displayed and few textboxes (where is edit other properties for roles). The kendo grid for roles have checkboxes and Rolenames. My current code is working if I select one checkbox.
What I need is how I get the array of the ids of the roles if I check multiple checkboxes. Tried multiple ways but I am not getting the list of ids when multiple checkboxes are selected. On click edit of the node EditNode is triggered and on click of save the 'click' is trigerred.
Below is my code:
function editNode(itemid) {
var editTemplate = kendo.template($("#editTemplate").html());
var treeview = $("#treeview").data("kendoTreeView");
var selectedNode = treeview.select();
var node = treeview.dataItem(selectedNode);
$("<div/>")
.html(editTemplate({ node: node }))
.appendTo("body")
.kendoWindow({
title: "Node Details",
modal: true,
open: function () {
console.log('window opened..');
editDS = new kendo.data.DataSource({
schema: {
data: function (response) {
return JSON.parse(response.d); // ASMX services return JSON in the following format { "d": <result> }.
},
model: {// define the model of the data source. Required for validation and property types.
id: "Id",
fields: {
Id: { editable: false, nullable: false, type: "string" },
name: { editable: true, nullable: true, type: "string" },
NodeId: { editable: false, nullable: false, type: "string" },
}
},
},
transport: {
read: {
url: "/Services/MenuServices.asmx/getroles",
contentType: "application/json; charset=utf-8", // tells the web service to serialize JSON
type: "POST", //use HTTP POST request as the default GET is not allowed for ASMX
datatype: "json",
},
}
});
rolesGrid = $("#kgrid").kendoGrid({
dataSource: editDS,
height: 150,
pageable: false,
sortable: true,
binding: true,
columns: [
{
field: "name",
title: "Rolename",
headerTemplate: '<span class="tbl-hdr">Rolename</span>',
attributes: {
style: "vertical-align: top; text-align: left; font-weight:bold; font-size: 12px"
}
},
{
template: kendo.template("<input type='checkbox' class = 'checkbox' id='chkbx' data-id='#:Id #' />"),
attributes: {
style: "vertical-align: top; text-align: center;"
}
},
],
}).data('KendoGrid');
},
})
.on("click", ".k-primary", function (e) {
var dialog = $(e.currentTarget).closest("[data-role=window]").getKendoWindow();
var textbox = dialog.element.find(".k-textbox");
var LinKLabel = $('#LL').val();
var roles = $(chkbx).data('roleid');
console.log(PageLocation);
node.text = undefined;
node.set("LINK_LABEL", LinKLabel);
node.set("Roles", roles);
dialog.close();
var treenode = treeview.dataSource.get(itemid);
treenode.set("LINK_LABEL", LinKLabel);
treenode.set("id", Id);
treenode.set("roles", roles);
treenode.LINK_LABEL = LinKLabel;
treenode.ID = Id;
treenode.roles = roles;
var rid = $(chkbx).data('roleid');
$.ajax({
url: "/Services/MenuServices.asmx/UpdateTreeDetails",
contentType: "application/json; charset=utf-8",
type: "POST",
datatype: "json",
data: JSON.stringify({ "Json": treenode })
});
console.log(JSON.stringify(treenode));
})
}
I'm assuming you want to get those ids in this line:
var roles = $(chkbx).data('roleid');
Right? What I don't know is the format you want to get that data. With the following code you can get the roles data in an array objects like this { id: 1, value: true }, check it out:
var grid = $("#grid").data("kendoGrid"),
ids = [];
$(grid.tbody).find('input.checkbox').each(function() {
ids.push({
id: $(this).data("id"),
value: $(this).is(":checked")
});
});
Demo. Anyway you want it, you can change it inside the each loop.
Update:
To get only the checked checkboxes, change the selector to this:
$(grid.tbody).find('input.checkbox:checked')
Demo

cannot display a table of data received from an ajax request in asp. net web api

I am trying to display a table of data returned by the following restful web api service accessible by this url. The problem is it displays only the header of the table and not the content.
/SMART/api/Build/GetAll
This url will return as output an IList of object called release, I have already tested this. The release object is structured as follows.
[Table("releases")]
public class Release
{
[Key]
public int Id { get; set; }
[StringLength(10)]
[Column("Name")]
public string Name { get; set; }
[StringLength(10)]
[Column("Type")]
public string Type { get; set; }
[Column("to_be_displayed")]
public bool ToBeDisplayed { get; set; }
}
Here is my javascript code
$.ajax({
type: 'GET',
url: '/SMART/api/Build/GetAll',
dataType: 'json',
contentType: "application/json",
success: function (data) {
alert(data);
// Get the JSON Data
var Data = new kendo.data.DataSource({
schema: {
model: {
id: "release.id",
fields: {
id: { type: "string" },
Name: { type: "string" },
Type : {type : "string"},
ToBeDisplayed: { type: "boolean" },
}
}
}
});
//Create a tab for the wip release
$('#listGrid').kendoGrid({
scrollable: false,
sortable: true,
resizable: true,
filterable: true,
autoSync: true,
dataSource: Data,
columns: [
{ field: "release.id", title: "Id" },
{ field: "release.Name", title: "Name" },
{ field: "release.ToBeDisplayed", title: "To be displayed", template: "<input name='ToBeDisplayed' type='checkbox' data-bind='checked: ToBeDisplayed' #= ToBeDisplayed ? checked='checked' : '' # class='build-tobedisplayed-checkbox'/>" },
]
});
}
});
Here is my cshtml code
<div id="listGrid" class="k-grid-content">
<div class="k-loading-mask" style="width:100%;height:100%"><span class="k-loading-text">Loading...</span><div class="k-loading-image"><div class="k-loading-color"></div></div></div>
</div>
Try the following Code:
function definitionUserGrid() {
var baseUrl = '/SMART/api/Build/GetAll';
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: baseUrl,
dataType: "json"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return {
models: kendo.stringify(options.models)
};
}
}
},
batch: true,
pageSize: 15
});
$("#listGrid").kendoGrid({
dataSource: dataSource,
pageable: true,
reorderable: true,
resizable: true,
sortable: true,
filterable: {
mode: "row"
},
columns: [
{field: "Id",
title: "Id",
}, {
filterable: {
cell: {
enabled: true,
showOperators: false,
operator: "contains"
}
},
field: "Name",
title: "Name"
}, {
filterable: {
cell: {
enabled: true,
showOperators: false,
operator: "contains"
}
},
field: "ToBeDisplayed",
title: "To be displayed",
template: "<input name='ToBeDisplayed' type='checkbox' data-bind='checked: ToBeDisplayed' #= ToBeDisplayed ? checked='checked' : '' # class='build-tobedisplayed-checkbox'/>" },
}]
});
}
And finally:
call function definitionUserGrid()
$(function(){
definitionUserGrid();
});

How to render Kendo UI grid from AJAX response data?

I have this code that gets json object from a static url and then renders grid. But I want to use json data retrived as AJAX response and then render grid using this response text. Because for practical deployment I can't use static URL.
$("#grid").kendoGrid({
dataSource: {
type: "json",
transport: {
read: {url: "http://url/returnsjsonobject.php"}
//THIS GETS DATA FROM STATIC URL BUT I WANT TO READ DATA AS AJAX RESPONSE
//like read: somefunctioncall
//or like read: somevariable
},
schema: {
model: {
fields: {
id: {type: "string", editable: false},
name: {type: "string"}
}
}
},
pageSize: 20
},
height: 430
columns: [
{field: "id", title: "ID", width: "20px", hidden: "true"},
"name",
});
Thanks in advance for help and if you have any alternative method; I will be happy to try it.
Remember that transport.read.url does not have to be a constant but might be a function:
transport: {
read: {
url: function(options) {
return "somefunctionalcall?id=" + options.id,
},
dataType: "json"
}
or even define transport.read as a function:
transport: {
read: function (options) {
$.ajax({
dataType: "json",
url: "somefunctionalcall",
success: function (d) {
options.success(d);
}
});
}
}

Kendo UI Grid - Update not persisting

Been trying to do an update on a Kendo grid and I'm having issues.
I'm using Rails as the back-end and when I do the update, the server seems to be showing that everything worked:
Started PUT "/" for 127.0.0.1 at 2012-02-12 17:28:19 -0600
Processing by HomeController#index as
Parameters: {"models"=>"[{\"created_at\":\"2012-02-08T17:34:50Z\",
\"first_name\":\"Milla\",\"id\":2,\"last_name\":\"sfasfsdf\",\"password\":\"\",
\"updated_at\":\"2012-02-08T17:34:50Z\",\"user_name\"
:\"\"}]"}
Rendered home/index.html.erb within layouts/application (3.0ms)
Completed 200 OK in 89ms (Views: 88.0ms | ActiveRecord: 0.0ms)
However, when I refresh the view, nothing has changed. When I checked the database, of course no changes had taken place there either.
I went through the documentation here about how to do edits in the grid: http://demos.kendoui.com/web/grid/editing.html
And I watched Burke Hollands video about how to set up the grid to work with Rails: http://www.youtube.com/watch?v=FhHMOjN0Bjc&context=C3f358ceADOEgsToPDskKlwC22A9IkOjYnQhYyY9HI
There must be something that I haven't done right, but I'm just not seeing it.
Here's my code that works with the Kendo stuff:
var User = kendo.data.Model.define({
id: "id",
fields: {
first_name: { validation: { required: true } },
last_name: { validation: { required: true } }
}
});
var UsersData = new kendo.data.DataSource({
transport: {
read: {
url: "/users.json"
},
create: {
url: "/users/create.json",
type: "POST"
},
update: {
type: "PUT"
},
destroy: {
type: "DELETE"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
},
batch: true,
pageSize: 5,
schema: {
model: User
}
});
$("#users-grid").kendoGrid({
dataSource: UsersData,
navigatable: true,
editable: true,
selectable: true,
pageable: true,
sortable: true,
toolbar: ["create", "save", "cancel"],
columns: [
{
field: "first_name",
title: "First Name"
},
{
field: "last_name",
title: "Last Name"
},
]
});
Some more research and I've got it working like this...
I added a route to override the 7 RESTful routes that Rails gives you by default. In your Routes.rb files, add this line...
match 'users' => 'users#update', :via => :put
Which basically says we are going to handle all puts by going to the update definition on the controller.
Now in the controller definition, you want to handle the update a bit differently since it's not RESTful. You need to first parse the JSON that you are sending via the parameterMap and then iterate through the objects updating with the object attributes...
def update
respond_to do |format|
#users = JSON.parse(params[:models])
#users.each do |u|
user = User.find(u["id"])
unless user.nil?
user.update_attributes u
end
end
format.json { head :no_content }
end
end
You can also modify your datasource because the url key can take a function:
var UsersData = new kendo.data.DataSource({
transport: {
read: {
url: '/users.json',
dataType: 'json'
},
update: {
url: function (o) {
return '/users/' + o.id + '.json'
},
dataType: 'json',
type: 'PUT'
},
destroy: {
url: function (o) {
return '/users/' + o.id + '.json'
},
dataType: 'json',
type: 'DELETE',
},
create: {
url: '/users.json',
dataType: 'json',
type: 'POST'
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
},
batch: true,
pageSize: 5,
schema: {
model: User
}
});

Categories