How I write a dynamic URL in kendo UI DataSource like "update/{id}" - kendo-ui

I have a web API. In that I wrote a update method. But it need to id of the table row to update to the row.
I use a grid to show data and use a toolbar to edit the row.
My question is how I pass that id to the update.
Can someone guide me ??

update: function(options) {
$.ajax( {
url: function(data) { return "updateUsuarios/"+data.Id,
dataType: "json",
.....

Well i suggest you, explain more your question, but i think this examples could help , if you have a toolbar as a template like this:
<script type="text/x-kendo-template" id="template">
<div class="toolbar">
<button type="button" id="update">Update</button>
</div>
</script>
You "grid" need the attr "toolbar"
$("#grid").kendoGrid({
dataSource: dataSource,
pageable: true,
height: 550,
filterable:true,
toolbar: kendo.template($("#template").html()),
columns: [
{ field:"username", title: "Username" , width: "120px" },
{ field: "nombre", title:"Nombre", width: "120px" },
{ field: "apellido", title:"Apellido", width: "120px" },
{ field: "ci", title:"Documento de Identidad", width: "120px" },
{ field: "email", title:"Direccion de Correo", width: "120px" },
{ field: "activo",title:"Estatus", width: "120px" },
{ field: "fecha_caducidad",title:"Fin Demo", width: "120px",template: "#= kendo.toString(kendo.parseDate(fecha_caducidad, 'yyyy-MM-dd'), 'MM/dd/yyyy') #" },
{ field: "licencia_status",title:" ", width: "40px",template:'<img src="assets/images/#:data.licencia_status#.png"/>' },
{ command: ["edit"], title: " ", width: "120px" }],
editable: "popup",
dataBound: function () {
var rows = this.items();
$(rows).each(function () {
var index = $(this).index() + 1;
var rowLabel = $(this).find(".row-number");
$(rowLabel).html(index);
});
},
selectable: true
});
So,you can configure a kendo button and add functionality in the event click:
$("#update").kendoButton({
click: function(){
//Here you will have the selected row
var self=$('#grid').data('kendoGrid')
var index = self.items().index(self.select());
var rowActual= self.dataSource.data()[index];
rowActual=self.dataItem(self.select());
if(rowActual==undefined || rowActual ==null) {
alert("No row selected");
}else{
$.ajax({
type: "POST",
url: "update",
data: {
id:rowActual.id
},
dataType: 'json',
success: function (data) {
},
error: function(){
}
});
}
}
});
and send in the ajax the row id, but if you are update the row with the inline edition you could try with a datasource like this
dataSource = new kendo.data.DataSource({
transport: {
read: function(options) {
$.ajax( {
url: "readUsuarios",
dataType: "json",
success: function(result) {
options.success(result);
}
});
},
update: function(options) {
$.ajax( {
url: "updateUsuarios",
dataType: "json",
data: {
models: kendo.stringify(options.data.models)
},
success: function(data) {
// response server;
},
error: function(result) {
// notify the data source that the request failed
options.error(result);
}
});
}
},
batch: true,
pageSize: 20,
schema: {
model: {
id: "id",
fields: {
username: { editable: false, nullable: true },
nombre: { validation: { required: true } },
apellido: { type: "string", validation: { required: true} },
ci: { type: "string", validation: { required: true} },
email: { type: "string", validation: { required: true } },
activo: { type: "boolean",editable: false },
fecha_caducidad: { type: "date" },
licencia_status:{editable: false}
}
}
}
});
I hope this help!

Related

Kendo UI posting null values to paramter in web api controller method

I am using the following code in cshtml,
Controller display null value in parameter,
I require values to be populated in controller method parameter,
Please help
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var crudServiceBaseUrl = "http://localhost:49885/api",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/Suppliers",
dataType: "json",
type: "Get"
},
update: {
url: function(data) {
debugger;
//return crudServiceBaseUrl + "/Suppliers/" + JSON.stringify(data.models[0]);
return crudServiceBaseUrl + "/Suppliers";
},
dataType: "json",
type: "Put",
contentType: "application/json"
},
destroy: {
url: function(data) {
debugger;
return crudServiceBaseUrl + "/Suppliers/" + JSON.stringify(data.SupplierId);
//return crudServiceBaseUrl + "/Suppliers";
},
//url: crudServiceBaseUrl + "/Suppliers",
dataType: "json",
type: "Delete",
contentType: "application/json"
},
create: {
url: function (data) {
debugger;
//return crudServiceBaseUrl + "/Suppliers/" + JSON.stringify(data);
return crudServiceBaseUrl + "/Suppliers";
},
//url: crudServiceBaseUrl + "/Suppliers",
dataType: "json",
type: "Post",
contentType: "application/json",
//data: JSON.stringify([data.SupplierId, data.CommId])
},
parameterMap: function(options, operation) {
debugger;
if (operation !== "read" && options) {
return { models: JSON.stringify(options) };
}
}
},
batch: false,
pageSize: 20,
schema: {
data: function(data) { //specify the array that contains the data
return data || [];
},
errors: function(response) {
return response.error;
},
model: {
id: "SupplierId",
fields: {
SupplierId: { validation: { required: true } },
CommId: { validation: { required: true } },
EmailId: { validation: { required: true } },
FullName: { validation: { required: true } },
FirstName: { validation: { required: true } },
Description: { validation: { required: true } },
LastName: { validation: { required: true } },
StateId: { validation: { required: true } }
}
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
navigatable: true,
pageable: true,
sortable: true,
height: 550,
toolbar: ["create", "save", "cancel"],
columns: [
"SupplierId",
{ field: "SupplierId", title: "SupplierId", width: 120 },
{ field: "CommId", title: "CommId", width: 120 },
{ field: "EmailId", title: "EmailId", width: 120 },
{ field: "FullName", width: 120 },
{ field: "FirstName", width: 120 },
{ field: "Description", width: 120 },
{ field: "LastName", width: 120 },
{ field: "StateId", width: 120 },
{ command: "destroy", title: " ", width: 150 }
],
editable: true
});
});
</script>
<div id="example">
<div id="grid"></div>
</div>

Kendo UI call custom service for delete

How can I call custom service for deleting a row in Kendo UI grid.This custon service should have a confirmation dialog option that can be customized.
Any thoughts on this is highly appreciative
You should customize the kendo.data.DataSource 'destroy' attribute to specify the URL and update the kendoGrid 'delete' command code for the custom confirmation.
Example code
$(document).ready(function () {
var windowTemplate = kendo.template($("#windowTemplate").html());
var crudServiceBaseUrl = "http://demos.kendoui.com/service",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/Products",
dataType: "jsonp"
},
update: {
url: crudServiceBaseUrl + "/Products/Update",
dataType: "jsonp"
},
destroy: {
url: crudServiceBaseUrl + "/Products/Destroy",
dataType: "jsonp"
},
create: {
url: crudServiceBaseUrl + "/Products/Create",
dataType: "jsonp"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
},
batch: true,
pageSize: 20,
schema: {
model: {
id: "ProductID",
fields: {
ProductID: { editable: false, nullable: true },
ProductName: { validation: { required: true } },
UnitPrice: { type: "number", validation: { required: true, min: 1} },
Discontinued: { type: "boolean" },
UnitsInStock: { type: "number", validation: { min: 0, required: true } }
}
}
}
});
var window = $("#window").kendoWindow({
title: "Are you sure you want to delete this record?",
visible: false, //the window will not appear before its .open method is called
width: "400px",
height: "200px",
}).data("kendoWindow");
var grid = $("#grid").kendoGrid({
dataSource: dataSource,
pageable: true,
height: 430,
toolbar: ["create"],
columns: [
"ProductName",
{ field: "UnitPrice", title: "Unit Price", format: "{0:c}"},
{ field: "UnitsInStock", title:"Units In Stock"},
{ field: "Discontinued"},
{ command: [
{name: "edit"},
{name: "Delete",
click: function(e){ //add a click event listener on the delete button
var tr = $(e.target).closest("tr"); //get the row for deletion
var data = this.dataItem(tr); //get the row data so it can be referred later
window.content(windowTemplate(data)); //send the row data object to the template and render it
window.open().center();
$("#yesButton").click(function(){
grid.dataSource.remove(data) //prepare a "destroy" request
grid.dataSource.sync() //actually send the request (might be ommited if the autoSync option is enabled in the dataSource)
window.close();
})
$("#noButton").click(function(){
window.close();
})
}
}
]}],
editable: {
mode: "inline"
}
}).data("kendoGrid");
});
Taken from:
http://docs.telerik.com/kendo-ui/web/grid/how-to/Editing/custom-delete-confirmation-dialog
You can set the delete option in your datasource to a function and do anything you want from that point. Without a sample of your service, I can't help you getting started but I can link you to the documentation.

InCell Editing in Kendo UI and Web API

I am new to Web API and Kendo UI. My requirement is InCell Editing. I have implemented this with below reference links. But my problem is In controller action method i am getting count of employee as 0. I am not any other things means edited rows.
http://demos.telerik.com/kendo-ui/grid/editing
http://demos.telerik.com/aspnet-mvc/grid/editing
and another way I tried with below reference. But here also in JQuery I am getting what I updated rows. but when passing data to controller through AJAX call in controller I am getting count as 0. Please can you help this.
http://stackoverflow.com/questions/17033025/kendo-grid-batch-editing-making-a-single-call-to-save
Here is my code:
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "/api/Employee/GetEmployee",
dataType: "json"
},
create: {
url: "/api/Employee/CreateEmployee",
dataType: "json",
type: "POST",
complete: function (jqXhr, textStatus) {
// Do something
}
},
update: {
url: "/api/Employee/Update",
dataType: "json",
type: "POST",
complete: function (jqXhr, textStatus) {
// Do something
}
},
destroy: {
url: "/api/Employee/DeleteEmployee",
dataType: "json",
type: "DELETE",
complete: function (jqXhr, textStatus) {
// Do something
}
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
batch: true,
pageSize: 12,
schema: {
model: {
id: "Id",
fields: {
Id: { editable: false, type: "number" },
EmployeeId: {
editable: true, type: "text", validation: {required: true },
},
EmployeeName: { validation: { required: true } }
}
}
}
});
if (container.find('#gridEmployee').data().kendoGrid)
container.find('#gridEmployee').data().kendoGrid.destroy();
container.find("#gridEmployee").kendoGrid({
dataSource: dataSource,
pageable: true,
// toolbar: [{ text: "Add new Employee", className: "btn btn-primary grid-add-new-record" }, { text: "Save", className: "btnKendoUiSave" }],
toolbar: ["create", "save", "cancel"],
columns: [
{
command: [
//define the commands here
{ name: "edit", text: " " }, { name: "destroy", text: " " }, { name: "update", text: " ", click: showDetails }], width: "200px"
},
{ field: "EmployeeId", title: "Employee Id", format: "{0:0}", headerAttributes: { "data-localize": "FIELD_NUMBER" } },
{ field: "EmployeeName", title: "Employee Name", headerAttributes: { "data-localize": "FIELD_NAME" } },
],
editable: true,
});
Web API Controller:
[HttpPost]
public System.Web.Mvc.JsonResult Update([System.Web.Mvc.Bind(Prefix = "models")]List<PlantEmployeeModel> Employees)
{
//
}

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;

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