kendo ui how to filter dataSource requestStart - kendo-ui

Main Problem
My current problem is the refresh progress when updating a grid datasource. I have change my code use the kendo.ui.progress in that way when requestStart event starts I ser the kendo.ui.progress to true. This activates the loading image when it end it calls the requestEnd.
The problem is that this event is hapenning for sorting and filtering. And I want it to only trigger for the read function of the dataSource. This problem makes the grid to use the progress endlessly.
Is there some way to filter in the requestStart and requestEnd only activate on the transport read?
My DataSource Code
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: url_Obtener_Periodo,
type: "POST"
},
parameterMap: function (options, operation) {
if (operation == "read" && options) {
return {
"periodo.Year": $("#periodo-anio").val(),
"periodo.Month": $("#periodo-mes").val(),
"Filtro": $("#Filtro").val()
};
}
}
},
requestStart: function (e) {
kendo.ui.progress($("#grid-container"), true);
},
requestEnd: function (e) {
kendo.ui.progress($("#grid-container"), false);
},
schema:{
model: {
id: "Codigo_De_Pedido",
fields: {
Codigo_De_Pedido: { type: "number" },
Fecha_Y_Hora_De_Creacion: { type: "date" },
UserName: { type: "string" },
Nombre_Del_Usuario: { type: "string" },
Codigo_Del_Vendedor: { type: "number" },
Nombre_Del_Vendedor: { type: "string" },
Is_Pedido_Closed: { type: "bool" },
Estado: { type: "string" }
}
}
},
pageSize: 10
});

The changes I did to solve the progress endlessly problem where 2.
Removing requestEnd function from the dataSource
Adding dataBound function to the Grid
Data Source Code
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: url_Obtener_Periodo,
type: "POST"
},
parameterMap: function (options, operation) {
if (operation == "read" && options) {
return {
"periodo.Year": $("#periodo-anio").val(),
"periodo.Month": $("#periodo-mes").val(),
"Filtro": $("#Filtro").val()
};
}
}
},
schema:{
model: {
id: "Codigo_De_Pedido",
fields: {
Codigo_De_Pedido: { type: "number" },
Fecha_Y_Hora_De_Creacion: { type: "date" },
UserName: { type: "string" },
Nombre_Del_Usuario: { type: "string" },
Codigo_Del_Vendedor: { type: "number" },
Nombre_Del_Vendedor: { type: "string" },
Is_Pedido_Closed: { type: "bool" },
Estado: { type: "string" }
}
}
},
pageSize: 10,
requestStart: function (e) {
kendo.ui.progress($("#grid-container"), true);
}
});
Kendo Grid Code
kendoGrid = $("#selectable-pedidos").kendoGrid({
dataSource: dataSource,
pageable: true,
sortable: true,
filterable: {
extra: false,
operators: {
string: {
startswith: "Comienza Con",
eq: "Es Igual A",
neq: "No Es Igual A"
}
}
},
dataBound: function (e) {
kendo.ui.progress($("#grid-container"), false);
},
columns: [
{ field: "Fecha_Y_Hora_De_Creacion", title: "Fecha y Hora", template: "#= kendo.toString(Fecha_Y_Hora_De_Creacion, 'dd/MM/yyyy hh:mm:ss tt') #" },
{ field: "Codigo_De_Pedido", title: "Código de Pedido" },
{ field: "Estado", filterable: true, title: "Estado" },
{ field: "Codigo_Del_Vendedor", title: "Código de Vendedor" },
{ field: "Nombre_Del_Vendedor", title: "Nombre de Vendedor" },
{
command: {
text: "Ver Detalle de Pedido",
click: function (e) {
$("#empty").append("<form method='POST' action='/HojaDeRuta/GetById/'><input type='hidden' name='Codigo_Pedido' value='"
+ this.dataItem($(e.currentTarget).closest("tr")).Codigo_De_Pedido + "' /><input type='submit' /></form>");
$("#empty input[type='submit']").click();
}
},
title: " "
}
]
}).data("kendoGrid");

There are a few things about your questions worth mentioning for those who read this:
Is there some way to filter in the requestStart and requestEnd only
activate on the transport read?
Yes, but it will not help you. The parameter of the event has a type property that will contain read, update, destroy or create.
statementEntriesDS.bind("requestStart", function (e) {
switch (e.type) {
case "create":
alert('-> event, type "create".');
break;
case "read":
alert('-> event, type "read".');
break;
case "update":
alert('-> event, type "update".');
break;
case "destroy":
alert('-> event, type "destroy".');
break;
}
});
Your example code doesn't specify serverFiltering or serverSorting so sorting and filtering wouldn't cause an remote action. You'll only get client-side sorting and filtering. However, if they are specified they're all going to result in a read and that wouldn't really help you.
That you would not have the requestEnd event fire sounds odd. You should probably add a handler for the error event and see if something is failing.
If you really want complete control over what's happening, you can specify a function for your read:
transport: {
read: function (options) {
kendo.ui.progress($gridContainer, true);
$.ajax({
url: carrierServiceBaseUrl + "/GetManualStatementsCarrierList",
contentType: 'application/json; charset=utf-8',
dataType: "json",
type: "POST",
success: function (result) {
// notify the data source that the request succeeded
options.success(result);
kendo.ui.progress($gridContainer, false); },
error: function (result) {
options.error(result); // Call the DataSource's "error" method with the results
kendo.ui.progress($gridContainer, false);
notification.show({
title: "ERROR:",
message: result.statusText
}, "error");
}
});
}
}

Related

How to get field value when edit data in Kendo Ui treelist

I'm new in Kendo UI,and i have a question. Now i'm use TreeList / Editing and how to auto load value to other field when i edit value to first field ?
example:
1.serial number: 123456789
2.name : test
when i edit serial number 123456789 to first field and auto load name to second field.
To set the value of column B based on change made to a column A, you need to edit the model bound to the tree list. For this do the following:-
Handle edit event of the tree list. On this save the model to a
local variable.
Add an editor
template
to column A. On the select event set the value of model.
Below is a working code snippet:-
<div id="treelist"></div>
<script>
$(document).ready(function () {
var crudServiceBaseUrl = "https://demos.telerik.com/kendo-ui/service";
var model= null;
var employeesData=[{"EmployeeId":101,"FirstName":"Daryl","LastName":"Sweeney"},
{"EmployeeId":202,"FirstName":"Guy","LastName":"Wooten"},
{"EmployeeId":303,"FirstName":"Priscilla","LastName":"Frank"},
{"EmployeeId":404,"FirstName":"Ursula","LastName":"Holmes"},
{"EmployeeId":505,"FirstName":"Anika","LastName":"Vega"}];
var dataSource = new kendo.data.TreeListDataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/EmployeeDirectory/All",
dataType: "jsonp"
},
update: {
url: crudServiceBaseUrl + "/EmployeeDirectory/Update",
dataType: "jsonp"
},
destroy: {
url: crudServiceBaseUrl + "/EmployeeDirectory/Destroy",
dataType: "jsonp"
},
create: {
url: crudServiceBaseUrl + "/EmployeeDirectory/Create",
dataType: "jsonp"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
},
batch: true,
schema: {
model: {
id: "EmployeeId",
parentId: "ReportsTo",
fields: {
EmployeeId: { type: "number", nullable: false },
ReportsTo: { nullable: true, type: "number" },
FirstName: { validation: { required: true } },
HireDate: { type: "date" },
Phone: { type: "string" },
HireDate: { type: "date" },
BirthDate: { type: "date" },
Extension: { type: "number", validation: { min: 0} },
Position: { type: "string" }
},
expanded: true
}
}
});
$("#treelist").kendoTreeList({
dataSource: dataSource,
toolbar: [ "create", "save", "cancel" ],
editable: "incell",
height: 540,
dataBound: function (e) {
var items = e.sender.items();
for (var i = 0; i < items.length; i++) {
var dataItem = e.sender.dataItem(items[i]);
var row = $(items[i]);
if (dataItem.isNew()) {
row.find("[data-command='createchild']").hide();
}
else {
row.find("[data-command='createchild']").show();
}
}
},
edit: function(e) {
model = e.model;
},
columns: [{
field: "EmployeeId",
expandable: true,
title: "Serial Number",
width: 180,
editor: function(container, options) {
// create an input element
var input = $("<input/>");
// set its name to the field to which the column is bound ('lastName' in this case)
input.attr("name", options.field);
// append it to the container
input.appendTo(container);
// initialize a Kendo UI AutoComplete
input.kendoAutoComplete({
dataTextField: "EmployeeId",
dataSource: employeesData,
select: function(e) {
if(model !=null){
model.FirstName = e.dataItem.FirstName;
model.LastName = e.dataItem.LastName;
}
}
});
}
},
{ field: "FirstName", title: "First Name", width: 100 },
{ field: "LastName", title: "Last Name", width: 100 },
{ field: "Position", width: 100 },
{ field: "Phone", title: "Phone", width: 100 },
{ field: "Extension", title: "Ext", format: "{0:#}", width: 100 },
{ command: [{name: "createchild", text: "Add child"},"destroy" ], width: 240 }]
});
});
</script>
You can trigger your function when the row is being saved or when the edit field is being changed. Take a look at the list of events here and choose when exactly you want to make the changes. https://demos.telerik.com/kendo-ui/treelist/events
here is a example how to all a function when saving the changes: https://docs.telerik.com/kendo-ui/api/javascript/ui/treelist/methods/saverow
I´m not sure witch edit method you are using (inline, inCell or Popup edit mode) each method can use events like saveRow, beforeEdit...
Check all the events documentation here: https://docs.telerik.com/kendo-ui/api/javascript/ui/treelist#events

kendu ui grid after server update cells stay marked as "dirty"

i based this code on kendu grid ui code demo.
when ever i add a new record, it gets sent to the server side (c# handler)
and from there i convert json to object.. and so on.
the operation is successful and the request that kendu made is done with status code 200.
but for some reason the cells that were changed are still marked as "dirty" .
as a result of this any new row is sent with the first attempt since it thinks it needs to be sent again. here is my code:
jQuery("#getallDataBTN").click(
function () {
$("#grid").kendoGrid({
dataSource: {
transport: {
read: {
url: "/WallEHandler.ashx?command=getallPermissions",
dataType: "json"
},
create: {
url: "/WallEHandler.ashx?command=addPermission",
dataType: "json",
type:"post"
},
update: {
// url: "/WallEHandler.ashx?command=editPermission",
// dataType: "jsonp"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
schema: {
model: {
id:"Method",
fields: {
Method: { type: "string" , validation: { required: true }},
ServiceType: { type: "string" ,validation: { required: true }},
Role: { type: "string" ,validation: { required: true }},
Permission: { type: "string" ,validation: { required: true }},
ExtendedData: { type: "string" }
}
}
},
pageSize: 100,
batch: true,
},
height:850,
scrollable: true,
sortable: true,
filterable: true,
pageable: {
input: true,
numeric: false
},
columns: [
"Method",
"ServiceType",
"Role",
{ field: "Permission", editor: categoryDropDownEditor },
"ExtendedData"
],
navigatable: true,
toolbar: ["create", "save", "cancel"],
editable: true
//selectable: "row",
//save: function(e)
// {
//alert("Save");
// }
});
}
);
is there maybe somthing i need to return from the server to tell the grid that it was successful?
thanks for any help
i figured it out, it seems that the response of a successful request must return the same object as sent. (must be some sort of inside validation by kendu).
c#:
Response.Write(context.Request.Form["models"]);

Kendo ui grid filed with editor, pop up won´t close

I have a field on my kendo ui grid which uses an editor:
columns:[{ field:"Nome", title: "Nome" },{ field: "idTipoQuarto", title:"Tipo de Quarto", editor: tipoQuartoEditor},
In my model i have:
schema:
{
data: "data",
total: function(response)
{
return $(response.data).length;
},
model:
{
id: "idQuarto",
fields:
{
idQuarto: { editable: false, nullable: true },
Nome: { validation: { required: true } },
idTipoQuarto: { validation: { required: true }}
}
}
}
And my editor function is:
function tipoQuartoEditor(container, options)
{
$('<input data-text-field="Nome" data-value-field="Nome" data-bind="value:' + options.field + '"/>').appendTo(container).kendoDropDownList({
autoBind: false,
dataSource: new kendo.data.DataSource({
transport:
{
read:
{
url: "data/quartos.php",
},
parameterMap: function(options, operation)
{
if (operation !== "read" && options.models)
{
return {models: kendo.stringify(options.models)};
}
}
},
schema:
{
data: "data",
model:
{
id: "idTipoQuarto",
value: "Nome"
}
}
})
});
}
I can see the values when my popup is opened in the drop-down list, and i can post the selections to my database when clicking on the update/insert button, but the popup won´t disappear. It shows me an error that i don´t understand:
Object {xhr: Object, status: "parsererror", errorThrown: SyntaxError: Unexpected token A, sender: ht.extend.init, _defaultPrevented: false…}
What am i missing here, i have seen another post but with no luck adapting to my problem.
Anyone?
Thanks for your time, regards

DataSource transport.destroy called +1 times for each successive delete (recalled for previously deleted items)

I have a DataSource in my code that support destroy. In order to delete object from the it, i directly call remove, i.e.
myDataSource.remove(discardedData);
I get a behavior similar to this. However, unlike the linked thread, my destroy is not set to a function, so the solution does not help me.
My DataSource (i included all of it in case some of my configuration is to blame):
var QueueMessages = {
type: "aspnetmvc-ajax",
transport: {
read: {
url: BASE_URL + "api/QueueMessages/GetMessagesHeaders",
dataType: "json",
type: "GET",
beforeSend: function (req) {
req.setRequestHeader('Authorization', authService.getAuth());
}
},
destroy: {
url: BASE_URL + "api/QueueMessages/deleteMessage",
dataType: "json",
type: "DELETE",
beforeSend: function (req) {
req.setRequestHeader('Authorization', authService.getAuth());
}
}
},
schema: {
model: {
id: "id",
fields: {
profileName: { type: "string" },
queueType: { type: "string" },
acceptedAt: { type: "date" },
processedAt: { type: "date" },
BodyExcerpt: { type: "string" }
}
},
total: "total",
data: "data",
},
error: function (e) {
//throw user back to login page
if (e.errorThrown === "Unauthorized")
$rootScope.$apply($location.path('/'));
},
requestStart: function () {
},
requestEnd: function () {
},
pageSize: 50,
serverPaging: true,
serverFiltering: true,
serverSorting: true,
serverGrouping: true,
serverAggregates: true
};
I cant find any clues as to why this is happening.
thanks to OnaBai I found the problem.
consulting RFC 7231, i my changed the http DELETE response from 200 OK to 204 no content.

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)
{
//
}

Resources