Kendo grid and asp.net web api - javascript

I use open source edition of kendo web, my current version is Kendo UI Web
i'm using kendo ui and asp.net mvc 4
my kendo grid have this js code
<script>
$(document).ready(function () {
$("#grid").kendoGrid({
dataSource: {
type: "odata",
serverSorting: true,
serverFiltering: true,
serverPaging: true,
transport: {
read: {
url: "api/Usermanage",
dataType: "json",
contentType: "application/json"
},
create: {
url: "/api/Usermanage",
dataType: "json",
type: "POST"
},
update: {
url: function (UserModel) {
return "/api/articles/" + UserModel.ID
},
dataType: "json",
type: "PUT"
},
destroy: {
url: function (UserModel) {
return "/api/Usermanage/" + UserModel.ID
},
dataType: "json",
contentType: "application/json",
type: "DELETE"
},
update: {
url: function (UserModel) {
return "/api/Usermanage/" + UserModel.ID
},
dataType: "json",
type: "PUT"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
},
schema: {
data: function (response) {
if (response.value !== undefined)
return response.value;
else {
delete response["odata.metadata"];
return response;
}
},
total: function (response) {
return response['odata.count'];
},
model: {
fields: {
ID:"ID",
ID: { editable: false },
Name: { type: "string", editable: true, nullable: false, validation: { required: true } },
Roles: { type: "string" }
}
}
}
},
height: 430,
scrollable: {
virtual: true
},
toolbar: ["create"],
editable: "popup",
sortable: true,
columns: [
{ field: "Name", title: "UserName", width: 110 },
{ field: "Roles", title: "Role", width: 160 },
{ command: ["edit", "destroy"], title: " ", width: "160px" }
]
});
});
</script>
},
method of api controller is:
// DELETE api/usermanage/5
public void Delete(int id)
{
var name = db.UserProfiles.Find(id);
Membership.DeleteUser(name.UserName,true);
}
but it doesn't works, what i doing wrong?

All of your command urls are pointing to url: "/api/Usermanage/"
This has to be specific to your action inside of the controller so in this case it should be:
url: function (UserModel) {
return "/api/Usermanage/Delete/" + UserModel.ID
},

Related

jsgrid controller updateItem not invoked

I'm working on js-grid, when i try to update a column field, the updateitem function of the controller is not invoked, plus the field resets its old value. I'm placing alerts in the function but nothing is called. I'm also calling the onItemUpdating of the jsgrid, but it's not called. Code snippet of my jsgrid:
$("#jsGrid").jsGrid({
width: "100%",
height: "400px",
inserting: true,
editing: true,
sorting: true,
paging: true,
//width: "auto",
height: "auto",
pageSize: 10,
//data: clients,
autoload: true,
onItemUpdating: function(args) {
alert('grid update');
previousItem = args.previousItem;
},
controller: {
loadData: function() {
var d = $.Deferred();
$.ajax({
url: "http://192.168.1.141:8080/tickets",
type : "GET",
contentType : "application/json; charset=utf-8",
dataType: "json"
}).done(function(response) {
d.resolve(response);
//d.resolve(response.result);
//alert(response);
});
return d.promise();
},
updateItem: function(item) {
alert('update');
/*return $.ajax({
type: "POST",
url: "http://localhost:8080/save",
data: item
});*/
var d = $.Deferred();
$.ajax({
url: "http://192.168.1.141:8080/save",
type : "POST",
data: item
}).done(function(response) {
alert('success');
d.resolve(response);
//d.resolve(response.result);
//alert(response);
}).fail(function() {
alert('fail');
d.resolve(previousItem);
});
return d.promise();
},
},
fields: [
{ name: "id", type: "text", title: "id", width: 90, validate: "required" },
{ name: "name", type: "text", title: "name", width: 150 },
{ name: "crn", type: "text", title: "CRN", width: 200 },
{ name: "age", title: "age", type: "number", width: 50 }
]
});
Resolved by adding a control field, updateItem is invoked when the edit button is pressed in the control column:
$(function() {
$("#jsGrid").jsGrid({
height: "auto",
width: "100%",
filtering: true,
editing: true,
sorting: true,
paging: true,
autoload: true,
onItemUpdating: function(args) {
previousItem = args.previousItem;
},
pageSize: 10,
pageButtonCount: 5,
deleteConfirm: "Do you really want to delete the client?",
controller: {
loadData: function(filter) {
console.log(filter);
var d = $.Deferred();
$.ajax({
url: "http://localhost:8080/tickets",
type : "GET",
contentType : "application/json; charset=utf-8",
dataType: "json"
}).done(function(response) {
d.resolve(response);
}).fail(function() {
});
return d.promise();
},
updateItem: function(item) {
var d = $.Deferred();
$.ajax({
url: "http://localhost:8080/save",
type : "POST",
data: item
}).done(function(response) {
//alert('success');
d.resolve(response);
}).fail(function() {
d.resolve(previousItem);
});
return d.promise();
},
},
fields: [
{ name: "id", type: "text", title: "id", editing: false, width: 90, autosearch: true },
{ name: "name", type: "text", title: "name", editing: false, width: 150, autosearch: true },
{ name: "crn", type: "text", title: "CRN", editing: false, width: 200, autosearch: true },
{ name: "age", title: "age", type: "number", width: 50 },
{ type: "control",deleteButton: false }
]
});
});

How to pass JSON Data to KendoUI Grid

today i'm trying to implement a kendo gridview to my website, actually i'm using a webservice that give me a JSON Result.
This is the result:
[{"IdComponente":"8","NoParte":"12","Descripcion":"Componente A","CostoUnitario":"0.12"},{"IdComponente":"9","NoParte":"123","Descripcion":"Componente B","CostoUnitario":"0.23"},{"IdComponente":"10","NoParte":"1234","Descripcion":"Componente C","CostoUnitario":"0.54"},{"IdComponente":"11","NoParte":"12345","Descripcion":"Componente D","CostoUnitario":"0.90"},{"IdComponente":"12","NoParte":"123456","Descripcion":"Componente E","CostoUnitario":"1.25"},{"IdComponente":"13","NoParte":"1234567","Descripcion":"Componente F","CostoUnitario":"0.12"},{"IdComponente":"14","NoParte":"12345678","Descripcion":"Componente G","CostoUnitario":"0.12"},{"IdComponente":"16","NoParte":"123456789","Descripcion":"Componente H","CostoUnitario":"0.98"}]
And i'm using this script, the problem is that i don't get any error in the console, but it doesn't show me the information in the grid.
So, i don't know why, because the json result its okay..
<script>
$(document).ready(function () {
$.ajax({
type: "POST",
url: "WSComponentes.asmx/obtenerComponentes",
data: '',
contentType: "application/json; charset=utf-8",
dataType: "json", // dataType is json format
success: function OnSuccess(response) {
cargarGrid(response);
},
error: function onError(error) {
console.log(error.d);
},
});
});
function cargarGrid(datos) {
console.log(datos);
$("#grid").kendoGrid({
dataSource: {
dataType: 'json',
data: datos,
schema: {
data: "d",
type: "json",
model: {
fields: {
IdComponente: { editable: false, type: "string" },
NoParte: { editable: false, type: "string" },
Descripcion: { editable: false, type: "string" },
CostoUnitario: { editable: false, type: "string" }
}
}
},
pageSize: 10
},
height: 550,
groupable: true,
sortable: true,
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
},
columns: [{
field: "IdComponente",
title: "IdComponente",
}, {
field: "NoParte",
title: "NoParte"
}, {
field: "Descripcion",
title: "Descripcion"
}, {
field: "CostoUnitario",
title: "CostoUnitario",
}
]
});
}
</script>
You're not far away with what you have.. You need to declare a kendo.data.DataSource:
var dataSource = new kendo.data.DataSource({
dataType: 'json',
data: datos,
schema: {
model: {
fields: {
IdComponente: { editable: false, type: "string" },
NoParte: { editable: false, type: "string" },
Descripcion: { editable: false, type: "string" },
CostoUnitario: { editable: false, type: "string" }
}
}
},
pageSize: 10
});
Which is then used in your grid declaration like so:
$("#grid").kendoGrid({
dataSource: dataSource, ....
Here is a Dojo example to demonstrate implementation changes required.

how to use custom command buttons in kendo grid with ajax call using javascript

i have the problem to use the custom command buttons in kendo grid with ajax call using javascript call web api post action with dynamic parameters behind buttons click(start,Stop,Restart)
datasource
dataSource = new kendo.data.DataSource({
transport: {
read:
{
url: crudServiceBaseUrl + "WindowsService",
dataType: "json",
},
destroy:
{
url: crudServiceBaseUrl + "WindowsService/Delete/?deletedby=" + clientid,
type: "DELETE"
},
create:
{
url: crudServiceBaseUrl + "WindowsService/Post",
type: "POST"
//complete: function (e) {
// $("#grid").data("kendoGrid").dataSource.read();
//}
},
update:
{
url: crudServiceBaseUrl + "WindowsService/Put/",
type: "PUT",
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return {
models: kendo.stringify(options.models)
};
}
}
},
},
schema:
{
model:
{
id: "WindowsServiceId",
fields: {
WindowsServiceId: { editable: true, nullable: false, type: "int" },
ServiceName: { editable: true, nullable: true, type: "string" },
ServiceStatus: { editable: true, nullable: false, type: "string" },
}
}
}
});
kendo grid
$("#grid").kendoGrid({
dataSource: dataSource,
editable: "popup",
toolbar: ["create"],
columns: [
{
field:"ServiceName",
title: "Service",
width: '200px',
},
{
field: "ServiceStatus",
title: "Status",
width: '140px',
},
{
field: "CreatedDate",
title: "Date",
width: '140px',
},
{
command: [
{
name: "start",
text: "Start",
click: function (e) {
$.ajax({
method: "POST",
url: crudServiceBaseUrl + "WindowsService/Start?windowsserviceid=3c661827-01cf-e511-bcd8-3859f9fd735e"+"&clientid="+clientid
}).done(function (msg) {
alert("Service Started successfully");
}).fail(function () {
alert("service failed");
});
}
},
{
name: "stop",
text: "Stop",
click: function (e) {
$.ajax({
method: "POST",
url: crudServiceBaseUrl + "WindowsService/Stop?windowsserviceid=3c661827-01cf-e511-bcd8-3859f9fd735e"+"&clientid="+clientid
}).done(function (msg) {
alert("Service Stop successfully");
}).fail(function () {
alert("service failed");
});
}
},
{
name: "restart",
text: "Restart",
click: function (e) {
$.ajax({
method: "POST",
url: crudServiceBaseUrl + "WindowsService/ReStart?windowsserviceid=3c661827-01cf-e511-bcd8-3859f9fd735e"+"&clientid="+clientid
}).done(function (msg) {
alert("Service ReStarted successfully");
}).fail(function () {
alert("service failed");
});
}
},
{
name: "history",
text: "History",
click: function (e) {
alert("History");
}
}
]
}
],
//height: "500px",
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
},
}).data("kendoGrid")
;
html
<div id="grid"> </div>
i have the problem to pass the dynamic windowsserviceid which is unique id, now i just use the static id. its working with static value.
please help/guide me how to use the dynamic windowsserviceid in ajax function call. i appreciate your valuable time and effort. thanks in advance.
Finally I found the solution by accessing the Unique Id of row and then using that Id in my Button Clicks functions and it all worked for me perfect.
var tr = $(e.target).closest("tr"); //accessing a row in grid
var item = this.dataItem(tr); //accessing row items in the grid
var winServiceId = item.WindowsServiceId; //my Unique Id in a row
and finally used this winServiceId in my Button click functions.
This should work for you:
<div id="grid"></div>
<script>
$("#grid").kendoGrid({
columns: [
{ hidden: true, field: "id" },
{ field: "name" }
],
dataSource: [ { id: 1, name: "Jane Doe" }, { id: 2, name: "John Doe" } ]
});
</script>
You can read more about it here:
http://docs.telerik.com/kendo-ui/api/javascript/ui/grid#configuration-columns.headerAttributes
Then all you have to do is access the hidden field value in your function.
On another note, you should remove your functions from the grid definition and have them as separate functions that you call from within the grid def.

Kendo Angular - update data

i have a problem. I am using kendo in my Angular web api and i have a problem with updating data. This is my code.
$scope.documentListGridOptions = {
dataSource: {
type: "json",
transport: {
read: {
url: serviceBase + "Documents/GetListDocuments",
type: "POST",
dataType: "json",
contentType: 'application/json',
beforeSend: function (req)
{
req.setRequestHeader('Authorization', authGlobalService.getAuthorizationData().token);
}
},
parameterMap: function (options)
{
if (options.filter)
{
options.filter = options.filter.filters;
}
return JSON.stringify(options);
}
},
schema: {
data: "data",
total: "total"
},
pageSize: 5,
serverPaging: true,
serverSorting: true,
serverFiltering: true
},
selectable: 'row',
scrollable: false,
sortable: true,
filterable: {
extra: false
},
pageable: true,
change: function (idSelectedVote)
{
$scope.$apply(function ()
{
$scope.setSelected(idSelectedVote.sender.dataItem(idSelectedVote.sender.select()));
});
},
dataValueField: "id",
columns: [{
title: "Id dokumentu",
field: "documentId",
hidden: true
},{
title: "Nazwa dokumentu",
field: "nameDocument"
},{
title: "Opis",
field: "descriptionDocument"
},{
title: "Data dodania",
field: "dateAdded"
}]
};
Data are getting from database and all is fine. But when data will change i don't know how can i update my data. How can i make another request to database. Please for help.
edit:
var documentListGridOptionsRemote = new kendo.data.DataSource({
autoSync: true,
transport: {
read: {
method: 'POST',
url: serviceBase + "Documents/GetListDocuments",
data: { name: "eco" },
dataType: "jsonp",
beforeSend: function (req) {
req.setRequestHeader('Authorization', authGlobalService.getAuthorizationData().token);
}
},
update: {
method: 'POST',
url: serviceBase + "Documents/GetListDocuments",
dataType: "json",
beforeSend: function (req) {
req.setRequestHeader('Authorization', authGlobalService.getAuthorizationData().token);
}
}
}
});
$scope.documentListGridOptions = {
dataSource: documentListGridOptionsRemote,
schema: {
data: "data",
total: "total"
},
selectable: "row",
scrollable: false,
sortable: true,
filterable: {
extra: false
},
pageable: true,
columns: [
{ field: "documentId", title: "Id", hidden: true },
{ field: "nameDocument", title: "Nazwa dokumentu" },
{ field: "descriptionDocument", title: "Opis" },
{ field: "dateAdded", title: "Data dodania" },
{ field: "name", title: "Test" }
]
};
in your dataSource's transport, you need to specify the update property like this:
transport: {
read: {
url: serviceBase + "Documents/GetListDocuments",
type: "POST",
dataType: "json",
contentType: 'application/json',
beforeSend: function (req)
{
req.setRequestHeader('Authorization', authGlobalService.getAuthorizationData().token);
},
update: {
//you can have function for url if you need to customise you url
//like url:function(data){ serviceBase + "Documents/GetListDocuments("+data.id+");}
url: serviceBase + "Documents/GetListDocuments",
type: "POST",//properly dont need this one, as update is a 'PUT'
dataType: "json",
contentType: 'application/json',
beforeSend: function (req)
{
req.setRequestHeader('Authorization', authGlobalService.getAuthorizationData().token);
}
},
and use 'create' for add and 'destroy'
for the complete document, please check this document , and also i will recommend to use angular httpProvider interceptor to handle the authentication token so you dont have to have beforeSend in every request

KendoUI Grid not working with RequireJS

I have:
require(['jquery', 'kendo'], function($, kendo){
var activeGrid = $('#incomeGrid');
var incomeSource = new kendo.data.DataSource({
sort: {
field: "date",
dir: "desc"
},
batch: true,
transport: {
read: {
url: 'core/income-grid/read',
dataType: 'json',
type: 'get'
},
update: {
url: 'core/income-grid/update',
dataType: 'json',
type: 'post'
},
create: {
url: 'core/income-grid/create/',
dataType: 'json',
type: 'post'
},
destroy: {
url: 'core/income-grid/destroy/',
dataType: 'json',
type: 'post'
}
},
error: function (e) {
alert(e.errorThrown + "\n" + e.status + "\n" + e.xhr.responseText);
},
schema: {
data: "data",
total: 'total',
model: {
id: 'id',
fields: {
typeId: {
type: 'number'
}
}
}
},
change: function (e) {
if (e.action == "itemchange" || e.action == "remove") {
if (!activeGrid.ctrlDown) {
this.sync();
}
}
}
});
activeGrid.kendoGrid({
dataSource: incomeSource,
autoBind: true,
height: 152,
pageable: false,
filterable: false,
toolbar: kendo.template($("#incomeToolBar").html()),
edit: function (e) {
var ddl = e.container.find('[data-role=dropdownlist]').data('kendoDropDownList');
if (ddl) {
ddl.open();
}
},
columns: [
{
title: 'Date added',
field: 'date',
width: '90px',
filterable: false,
template: '<span data-id="#=id#"><abbr title="">#=kendo.toString(date, "dd/MM/yyyy")#</abbr></span>'
}
],
editable: true,
sortable: true,
scrollable: true
}).data("kendoGrid");
})
But on the line that has:
activeGrid.kendoGrid({
I am getting the error:
Uncaught TypeError: undefined is not a function
Any idea how I can fix this? It's been driving me mad for the past four hours...

Categories