Kendo grid returning only one record - kendo-ui

I´ve been searching all over the net to find an answer to this problem but with no success, my problem is with my Kendo ui grid which is returning just one record. The funny thing is, i have another grids that are returning all the records correctly, so i simply using the same code but there´s got be a detail that is escaping me so i was hopping someone could point on that, this is the code i´m using (CRUD):
var dataSource = new kendo.data.DataSource({
transport:
{
read:
{
url: "data/clientes.php",
},
update:
{
url: "data/clientes.php?type=update",
type:"POST",
complete: function(e)
{
$("#gridClientes").data("kendoGrid").dataSource.read();
}
},
destroy:
{
url: "data/clientes.php?type=destroy",
type: "POST"
},
create:
{
url: "data/clientes.php?type=create",
type: "POST",
complete: function (e) {
$("#gridClientes").data("kendoGrid").dataSource.read();
}
},
parameterMap: function(options, operation)
{
if (operation !== "read" && options.models)
{
return {models: kendo.stringify(options.models)};
}
}
},
error:function(e)
{
console.log(e);
//alert(e.message);
},
batch: true,
pageSize: 8,
schema:
{
data: "data",
total: function(response)
{
return $(response.data).length;
},
model:
{
id: "idCliente",
fields:
{
idCliente: { editable: false, nullable: true, type: "number"},
titulo: { validation: { required: false } },
primeiroNome: { validation: { required: true } },
ultimoNome: { validation: { required: true } },
morada: { validation: { required: false } },
codigoPostal: { type: "string",validation: { required: false} },
cidade: { validation: { required: false } },
pais: { validation: { required: false } },
estado: { validation: { required: false } },
telefone: { type: "string", validation: { required: false, min: 1} },
email: { validation: { required: false } },
passaporte: { validation: { required: false } },
bi: { type: "number", validation: { required: false} },
foto: { type: "string", validation: { required: false} },
comentarios: { validation: { required: false } },
NomeUtilizadorCriador: {editable: true,validation: { required: false } },
DataCriacao: {editable: false, validation: { required: false } },
NomeUtilizadorUpdate: {editable: true, validation: { required: false } },
DataUpdate: {editable: false, validation: { required: false } },
}
}
}
});
$("#gridClientes").kendoGrid({
dataSource: dataSource,
height: 550,
serverPaging: true,
pageable : true,
toolbar:[{name: "create",text: $varGridQuartosBtnNovoPT},{name: "close",text: "X"}],
editable : {mode : "popup",
window : {title: "Editar",}
},
columns: [
{ field: "titulo", title: "Título", width: "8px", },
{ field: "primeiroNome", title: "Primeiro Nome", width: "14px" },
{ field: "ultimoNome", title: "Ultimo Nome", width: "14px" },
{ field: "morada", title: "Morada", width: "11px" },
{ field: "cidade", title: "Cidade", width: "11px" },
{ field: "codigoPostal", title: "CEP", width: "9px", editor:numberEditor },
{ field: "pais", title: "País", width: "14px" ,editor: paisEditor},
{ field: "estado", title: "Estado", width: "10px", hidden: true },
{ field: "telefone", title: "Telefone", width: "12px",editor:numberEditor},
{ field: "email", title: "Email", width: "17px" },
{ field: "passaporte", title: "Passaporte", width: "15px", hidden: true },
{ field: "bi", title: "Bi", width: "10px", hidden: true ,editor:numberEditor},
{ field: "foto", title: "Foto", hidden: true, editor:fotoEditor},
{ field: "comentarios", title: "Comentários", hidden: true, editor: textareaEditor},
{ field: "NomeUtilizadorCriador", title: "Criado por", hidden: true,editor:numberEditor},
{ field: "DataCriacao", title: "Criado em", hidden: true, width: "10px"},
{ field: "NomeUtilizadorUpdate", title: "Atualizado por", hidden: true, editor:numberEditor},
{ field: "DataUpdate", title: "Atualizado em", hidden: true, width: "10px"},
{command:[{ text: "Detalhes", click: showDetails },{ name: "edit",text:"Editar"},{ name: "destroy",text:"Apagar"}],title:" ",width: "30px"}],
});
If my database is empty and i insert just one record, then it returns that record correctly, but if i hit the new button to insert another record, it inserts in the database but the kendo grid returns/displays nothing, Meanwhile i have discovered a difference between this kendogrid and the others(that are working correctly) when i open the chrome console, this one returns two objects "data":
0: {,…}
data: {0: "70", 1: "", 2: "jonh", 3: "sousa", 4: "", 5: "", 6: "", 7: "", 8: "", 9: "", 10: "", 11: "",…}
1: {,…}
data: {0: "73", 1: "", 2: "joana", 3: "banana", 4: "", 5: "", 6: "", 7: "", 8: "", 9: "", 10: "", 11: "",…}
the other kendogrids, only return one object data, why? i do not know because i´m using the same code. I thought it could be something related with my .php file, but then if it was, it shouldn´t even insert one record right?.
I also have this error when i call the grid:
Object {xhr: Object, status: "parsererror", errorThrown: SyntaxError: Unexpected end of input, sender: ht.extend.init, _defaultPrevented: false…}
this error appears when my database is empty. If i have one record, then the erro disappears and as i said before the grid displays correctly, BUT the error returns if i insert another record.
Sorry for the long post, thanks for your time, any help would be very appreciated.
Regards

Related

kendo grid server re filtering the data source

$(document).ready(function () {
var agenciesData = new kendo.DataToken.DataSource({
type: 'webapi',
transport: {
read: { url: "/api/Agencies/", dataType: "json", data: { activity: getActivity() } },
create: { url: "/api/Agencies", type: "POST", dataType: "json" },
destroy: { url: "/api/Agencies/{0}", type: "DELETE" },
update: { url: "/api/Agencies/{0}", type: "PUT" },
idField: "ID"
},
filter: [{ field: "Activity", operator: "eq", value: getActivity() }],
pageSize: 15,
page: 1,
total: 0,
serverPaging: true,
serverSorting: true,
serverFiltering: true,
schema: {
data: "Data",
total: "Total",
model: {
id: "ID",
fields: {
ID: { editable: false, type: "number" },
AgencyName: { type: "string" },
AgentName: { type: "string" },
Address: { type: "string" },
City: { type: "string" },
Tel1: { type: "string" },
Tel2: { type: "string" },
Pele: { type: "string" },
Activity: { type: "number" },
ToDate: { type: "date" }
}
}
}
});
$("#agenciesGrid").kendoGrid({
dataSource: agenciesData,
toolbar: [{ text: "valid", className: "validAgents" }, { text: "not valid", className: "notValid" }, { text: "all", className: "allAgents" }, { text: "potential", className: "potetial" }],
editable: false,
navigatable: true,
sortable: true,
autoBind: false,
height: 430,
pageable: { refresh: true },
columns: [
{ field: "ID", hidden: true },
{ field: "AgencyName", title: "agency", width: 150, filterable: { cell: { operator: "contains" } } },
{ field: "AgentName", title: "agent", width: 150, filterable: { cell: { operator: "contains" } } },
{ field: "Address", title: "address", width: 200, template: "#= Address + ' ' + City #", filterable: false },
{ field: "Tel1", title: "phones", width: 300, template: "#= Tel1 + ' : ' + Tel2 + ' : ' + Pele #", filterable: false },
{ field: "Activity", title: "active", width: "90px" },
{ field: "ToDate", title: "end Contract", type: "date", width: 90, format: "{0:dd/MM/yyyy}", parseFormats: ["yyyy-MM-ddThh:mm:ss"] }
]
});
$(".validAgents").click(function () { //valid
$("#myActivity").val("1");
$('#agenciesGrid').data().kendoGrid.dataSource.read({ activity: "1" });
});
$(".notValid").click(function () {//notValid
$("#myActivity").val("2");
$('#agenciesGrid').data().kendoGrid.dataSource.read({ activity: "2" });
});
$(".potetial").click(function () {//potetial
$("#myActivity").val("3");
$('#agenciesGrid').data().kendoGrid.dataSource.read({ activity: "3" });
});
});
function getActivity(){
var myActivity = $("#myActivity").val();
return myActivity;
}
When I use kendo grid already filtered by parameter like : $('#someGrid').data().kendoGrid.dataSource.read({ activity: value });
i see the get: https://localhost:44305/api/Agencies/?sort=&page=1&pageSize=15&group=&filter=&activity=1
The grid is filter as expected but, when I want to do paging, sorting, refresh - I get the whole data ignoring the filter that i made.
and I see the get: https://localhost:44305/api/Agencies/?sort=&page=1&pageSize=15&group=&filter=
How can I save my filter state to do paging and sorting on the data came from the server side ?
even when i used differen approach like "scrollable: { virtual: true }" and when i scroll down - every request is without the filtering...
Thanks
Did you try
var agenciesData = new kendo.DataToken.DataSource({
filter : function () {
return object;
}
});
I mean try using filter as a function and you can do your logic inside the function depending on the situation.

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());

How do I bind the results of an AJAX GET call to a Kendo Grid?

Refer to the comment inside the AJAX done function below:
$("<div/>").appendTo(e.detailCell).kendoGrid({
reorderable: true,
resizable: true,
dataSource: {
transport: {
read: function()
{
$.ajax({
url: "http://x/y/api/Awards/directors/" + e.data.AwardTitleId,
type: "GET"
}).done(function()
{
//I'm not sure what to do here in order to bind the data returned by the GET to the grid.
});
},
},
schema: {
model: {
id: "namefirstlast",
fields: {
"namefirstlast": { editable: true, type: "string" },
"directorsequence": { editable: true, type: "number", validation: { min: 1 } },
"isonballot": { editable: true, type: "boolean" },
"concatenation": { editable: true, type: "string" },
"MoreNames": { editable: true, type: "number", validation: { min: 0 } },
},
},
}
},
columns: [
{ field: "namefirstlast", title: "Name", editor: namesAutoComplete },
{ field: "directorsequence", title: "Director Sequence", format: "{0:n0}" },
{ field: "isonballot", title: "On ballot?" },
{ 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" }]
});
Figured it out:
detailRow.find(".directorsOrRecipients").data("kendoGrid").dataSource.read();
detailRow.find(".directorsOrRecipients").data("kendoGrid").refresh();

Kendo grid - Posted Edit is null at Controller

Using kendo grid with Popup edit. I verified the data is posted from the view (I can see it in the Network Tab, here is a look at it:
{"LetterId":12,"BodyText":"This is a test","CreatedDate":"07/31/2013","CreatedBy":"Grace Rodgers","ModifiedDate":"07/31/2013","ModifiedBy":"Grace Rodgers","PersonId":18,"FirstName":"Jason","LastName":"Bigby"}:
However, I have a breakpoint at the json method in the controller, and when hovering over the model parameter, in shows all fields are null. Here is the first couple lines of the controller code:
[HttpPost]
public JsonResult JsonEditLetter(LetterViewModel model)
{
and the kendo code in the view:
var PersId = $("#PersonId").val();
var ds_LettersGrid = new kendo.data.DataSource({
transport: {
read: {
url: '#Url.Action("JsonGetLetterList", "Letter")/' + PersId,
dataType: 'json'
},
update: {
url: '#Url.Action("JsonEditLetter", "Letter")',
dataType: 'json',
type: "POST"
},
parameterMap: function (data, type) {
if (type == "update") {
data.models[0].CreatedDate = kendo.toString(new Date(data.models[0].CreatedDate), "MM/dd/yyyy");
data.models[0].ModifiedDate = kendo.toString(new Date(data.models[0].ModifiedDate), "MM/dd/yyyy");
return kendo.stringify(data.models[0]);
}
},
},
batch: true,
schema: {
model: {
id: "LetterId",
fields: {
BodyText: { editable: true },
CreatedDate: { editable: false, type: "date"},
ModifiedDate: { editable: false, type: "date" },
CreatedBy: { editable: false},
ModifiedBy: { editable: false },
PersonId: { defaultValue: PersId }
}
}
},
pageSize: 10
});
$(document).ready(function () {
$("#letter-list").kendoGrid({
dataSource: ds_LettersGrid,
sortable: true,
filterable: { extra: false, operators: {
string: { startswith: "Starts with", eq: "Is equal to" }
}
},
pageable: true,
columns: [{
field: "BodyText", title: "Letter Content", width: 400, filterable: false
}, {
field: "CreatedBy", title: "Author", filterable: false
}, {
field: "CreatedDate", title: "Original Date", format: "{0:g}", filterable: { ui: "datetimepicker" }
}, {
field: "ModifiedBy", title: "Edited By", filterable: false
}, {
field: "ModifiedDate", title: "Editted On", format: "{0:g}", filterable: { ui: "datetimepicker" }
}, {
command: [ "edit" ], title: "", width: "110px"
}],
height: "300px",
resizable: true,
editable: "popup"
});
});
You need to add default value to your id field , becouse the client side generates new id value, what you already have in server autoincrement generated id value and its shooting error
schema: {
model: {
id: "LetterId",
fields: {
LetterId: {defaultValue: 16000}
BodyText: { editable: true },
CreatedDate: { editable: false, type: "date"},
ModifiedDate: { editable: false, type: "date" },
CreatedBy: { editable: false},
ModifiedBy: { editable: false },
PersonId: { defaultValue: PersId }
}
}
}
I figured it out, it wanted a specific content type. The type being passed was a form, but the controller wanted json. So the Transport now looks like:
update: {
url: '#Url.Action("JsonEditLetter", "Letter")',
dataType: 'json',
>>>>>>>> contentType: "application/json",
type: "POST"
},

filter kendo ui grid with filed type object

I have this grid
$("#address-grid").kendoGrid({
dataSource: {
transport: {
read: {
url: "operations/get_sales_reps_addresses.php?salesRepsId=" + salesRepsId,
type: "GET"
},
update: {
url: "operations/edit_address.php?salesRepsId=" + salesRepsId,
type: "POST",
complete: function (e) {
$("#address-grid").data("kendoGrid").dataSource.read();
}
},
destroy: {
url: "operations/delete_address.php",
type: "POST",
complete: function (e) {
$("address-grid").data("kendoGrid").dataSource.read();
}
},
create: {
url: "operations/add_address.php?salesRepsId=" + salesRepsId,
type: "POST",
complete: function (e) {
$("#address-grid").data("kendoGrid").dataSource.read();
}
},
},
schema: {
data: "data",
total: "data.length", //total amount of records
model: {
id: "SalesRepId",
fields: {
AddressType: {
defaultValue: {
AddressTypeid: 1,
AddressTypeName: "Work"
}
},
Country: {
defaultValue: {
CountryId: 38,
CountryName: "Canada"
}
},
State: {
defaultValue: {
StateId: 4223,
StateName: "British Colombia"
}
},
City: {
defaultValue: {
CityId: 59450,
CityName: "Vancouver"
}
},
PostalCode: {
type: "string"
},
AddressText: {
type: "string"
},
IsMainAddress: {
type: "boolean"
},
AddressId: {
type: "integer"
}
}
}
},
pageSize: 3,
},
ignoreCase: true,
height: 250,
filterable: true,
sortable: true,
pageable: true,
reorderable: false,
groupable: false,
batch: true,
navigatable: true,
toolbar: ["create", "save", "cancel"],
editable: true,
columns: [{
field: "AddressType",
title: "Type",
editor: AddressTypeDropDownEditor,
template: "#=AddressType.AddressTypeName#",
}, {
field: "Country",
title: "Country",
editor: CountryDropDownEditor,
template: "#=Country.CountryName#",
}, {
field: "State",
title: "State",
editor: StateDropDownEditor,
template: "#=State.StateName#",
}, {
field: "City",
title: "City",
editor: CityTypeDropDownEditor,
template: "#=City.CityName#",
}, {
field: "PostalCode",
title: "Postal Code",
}, {
field: "AddressText",
title: "Address",
}, {
field: "IsMainAddress",
title: "Main?",
width: 65,
template: function (e) {
if (e.IsMainAddress == true) {
return '<img align="center" src ="images/check-icon.png" />';
} else {
return '';
}
}
// hidden: true
}, {
command: "destroy",
title: " ",
width: 90
},
]
});
The problem is when I try to filter by Country or State or City I got an error
TypeError: "".toLowerCase is not a function
I tried to change the type of Country to string, I use comobox, so the values were undefined. I also tried to change the type to Object, the values displayed correctly but I couldn't filter. I got the same error( toLowerCase)
How can I fix this ??
My grid is very similar this example
and here is the jsFiddle . I've just added the filter. and I still get previous error
I want to filter on the Category, any help ??
This is how you filter a dataSource Kendo dataSource , filter
So get the dataSource of your grid,
var gridDatasource = $("#address-grid").data('kendoGrid').dataSource;
and filter it like this example.
gridDatasource.filter({ ... });
If you provide a working jsFiddle, you may get a more specific answer.
Specific answer:
You added the filter, so for Category it didn't work because as I said, it is an observable, not a filed you can filter as a string.
So you must specify better your filter for this column, like this:
field: "Category",
title: "Category",
width: "160px",
editor: categoryDropDownEditor,
template: "#=Category.CategoryName#",
filterable: {
extra: false,
field:"Category.CategoryName",
operators: {
string: {
startswith: "Starts with",
eq: "Is equal to",
neq: "Is not equal to"
}
}
}
see this jsFiddle -- > http://jsfiddle.net/blackjim/Sbb5Z/463/

Resources