How to pass JSON Data to KendoUI Grid - javascript

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.

Related

Check only specific rows of kendo grid

I'm using a kendo grid on a edit modal. When the modal pops up i need to check the specific rows. this my kendo grid.
function LoadControllerGrid(list) {
var ListofrowIds = list
$("#controllerGrid1").kendoGrid({
dataSource: {
type: "json",
// contentType: "application/json; charset=utf-8",
transport: {
read: {
url: "#Html.Raw(Url.Action("GetControllerList", "Account"))",
type: "POST",
dataType: "json"
},
},
schema: {
model: {
id: "UserId",
fields: {
'Id': { type: "string" },
'Name': { type: "string" },
'Description': { type: "string" },
'URL': { type: "string" },
},
},
data: 'data',
total: 'TotalCount'
},
complete: function (jqXHR, textStatus) {
// HidePageLoader();
},
pageSize: 5,
serverPaging: true,
serverSorting: true,
serverFiltering: true,
columnMenu: true
},
height: 300,
groupable: false,
sortable: true,
filterable: true,
pageable: {
refresh: true,
pageSizes: 5000
},
columns: [{ template: '<input type="checkbox" class="checkbox" />', width: "35px" },
{ field: "Description", title: "Actions" }, ]
});
}
I pass the ids of specific rows that need to be checked to the function. kendo grid above display the all the rows.how can i check the check boxes of those particular rows.

Cannot update value in Kendo-grid - cannot read 'data' property of undegined

I am updating Kendo-grid when the selected value in option HTML element is changed. But when I try to update the value in the grid inline in the browser's console is printed "kendo.web.min.js:13 Uncaught TypeError: Cannot read property 'data' of undefined".
What Did I wrong?
< script >
$(document).ready(function() {
// on changing zone option selector
$('#SelectProviderZoneForPrices').change(function (e) {
var zoneId = $(this).val();
var productId = $('#SelectProviderForPrices').val();
$.ajax({
type: "GET",
url: "#Html.Raw(Url.Action("LoadZoneWeights", "ShippingZonableByWeight"))",
success: loadPrices, // loads the shipping providers which delivers by zones
dataType: 'json',
data: { ProviderId: productId, ZoneId: zoneId }});
});
// loads prices
function loadPrices(data) {
var grid = $('#shippingProviderWeightPrice-grid').getKendoGrid();
grid.dataSource.data(data.Data); // my backend returns DataSourceResult
grid.refresh();
}
// load Kendo-grid
$("#shippingProviderWeightPrice-grid").kendoGrid({
dataSource: {
type: "json",
transport: {
read: {
url: "#Html.Raw(Url.Action("ActionMethod", "Controller"))",
type: "GET",
dataType: "json"
},
update: {
url: "#Html.Raw(Url.Action("ActionMethod", "Controller"))",
type: "POST",
dataType: "json"
}
},
schema: {
total: "Total",
errors: "Errors",
model: {
fields: {
ProviderWeightsId: {
editable: false,
visible: false,
type: "number"
},
ZoneId: {
editable: false,
visible: false,
type: "number"
},
ZoneName: {
editable: false,
visible: false,
type: "string"
},
WeightFrom: {
editable: false,
visible: true,
type: "number"
},
WeightTo: {
editable: false,
visible: true,
type: "number"
},
Price: {
editable: true,
visible: true,
type: "number"
}
}
}
},
requestEnd: function(e) {
if (e.type == "update") {
this.read();
}
},
error: function(e) {
display_kendoui_grid_error(e);
this.cancelChanges();
},
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
pageable: {
refresh: true,
numeric: false,
previousNext: false,
info: false
},
editable: {
confirmation: true,
mode: "inline"
},
scrollable: false,
columns: [{
field: "WeightFrom",
title: "Weight From",
format: "{0:n3}",
width: 100
}, {
field: "WeightTo",
title: "Weight To",
format: "{0:n3}",
width: 100
}, {
field: "Price",
title: "Price",
format: "{0:n3}",
width: 100
}, {
command: [{
name: "edit",
text: "Edit"
}]
}]
});
}); < /script>
<fieldset>
<legend><strong>Manage Weights</strong>
</legend>
<table class="adminContent">
<tr>
<td class="adminTitle">Select Provider</td>
<td class="adminData">
<select id="SelectProviderForPrices" name="ProviderId">
<option value="0">- Select Provider -</option>
</select>
</td>
</tr>
<tr>
<td class="adminTitle">Select Zone</td>
<td class="adminData">
<select id="SelectProviderZoneForPrices" name="ProviderId">
<option value="0">- Select Zone -</option>
</select>
</td>
</tr>
</table>
</fieldset>
<br/>
<div id="shippingProviderWeightPrice-grid">
</div>
I found the problem. I was removed the id property in my datasource-model of the grid and that caused my problems. I don't know why it is so big deal - especially when I could have objects without ID. But now it is fine.
id: "ProviderWeightsId",
fields: {
ProviderWeightsId: { editable: false, visible: false, type: "number" },
ZoneId: { editable: false, visible: false, type: "number" },
ZoneName: { editable: false, visible: false, type: "string" },
WeightFrom: { editable: false, visible: true, type: "number" },
WeightTo: { editable: false, visible: true, type: "number" },
Price: { editable: true, visible: true, type: "number" }
}
You are not passing data to the loadPrices function.
$('#SelectProviderZoneForPrices').change(function (e) {
var zoneId = $(this).val();
var productId = $('#SelectProviderForPrices').val();
$.ajax({
type: "GET",
url: "#Html.Raw(Url.Action("LoadZoneWeights", "ShippingZonableByWeight"))",
success: function (data) {
loadPrices(data); //pass data to loadPrices function
}
dataType: 'json',
data: { ProviderId: productId, ZoneId: zoneId }});
});
Update:
Try this :
public ActionResult LoadZoneWeights(int ProviderId, int ZoneId)
{
var zoneWeights = _shippingService.GetZonesWithWeights(ProviderId, ZoneId);
return Json(zoneWeights , JsonRequestBehavior.AllowGet);
}
and
schema: {
data: function(response) {
return response.data;
}
}

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

How to use date type field in kendo ui Javascript in MVC

I am create one sample application and use kendo-ui inline editing grid.
Problem is: not come date field value in action controller.
View page Code is:
<script type="text/javascript">
$(document).ready(function () {
$("#grid").kendoGrid({
dataSource: {
type: "json",
transport: {
read: {
url: "#Html.Raw(Url.Action("CriticalDateList", "Home"))",
type: "POST",
dataType: "json"
},
create: {
url: "#Html.Raw(Url.Action("InsertCriticalDate", "Home"))",
type: 'POST',
dataType: "json"
},
},
change: function (e) {
if (e.action == "itemchange") {
e.items[0].dirtyFields = e.items[0].dirtyFields || {};
e.items[0].dirtyFields[e.field] = true;
}
},
batch: true,
schema: {
data: "Data",
total: "Total",
errors: "Errors",
model: {
id:"Id",
fields: {
Id: { editable: false},
Date: { editable: true, type: "date" },
}
}
},
error: function (e) {
//display_kendoui_grid_error(e);
this.cancelChanges();
},
pageSize:5,
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
pageable: true,
height: 500,
toolbar: ["create"],
columns: [
{field: "Date", title: "Date", format: "{0:dd-MMM-yyyy hh:mm:ss tt}", parseFormats: ["yyyy-MM-dd'T'HH:mm:ss.zz"], width: "130px"},
{ command: ["edit", "destroy"], title: "Action", width: "250px" }],
editable: "inline"
});
Action Code is:
public ActionResult InsertCriticalDate(CriticalDateModels model)
{
return null;
}
output is.
And in my action i am getting different date.

Setting a data item for "Create" in Kendo Grid

I need to pass an additional parameter along with my grids datasources create routine but I am having trouble getting it to work.
I have tried:
$('#contactPhonesGrid').data("kendoGrid").dataSource.dataItem.set('phoneId', phoneId)
but this gives me the error Cannot read property 'set' of undefined.
Code for my grid:
function contactPhoneGrid() {
var contactPhoneGrid = $('#contactPhonesGrid').kendoGrid({
dataSource: {
pageSize: 25,
serverSorting: false,
serverFiltering: true,
sort: {
field: "ref",
dir: "asc"
},
transport: {
read: {
url: ROOT + 'Contact/contactPhoneGrid',
dataType: 'json',
type: 'POST'
},
create: {
url: ROOT + 'Contact/createContactPhone',
type: 'POST'
},
update: {
url: ROOT+'Contact/updateContactPhone',
dataType: 'json',
type: 'POST'
},
destroy: {
url: ROOT+'Contact/deleteContactPhone',
dataType: 'json',
type: 'POST'
}
},
error: function(e) {
alert(e.errorThrown + "\n" + e.status + "\n" + e.xhr.responseText);
},
schema: {
data: "data",
model: {
id: 'phoneId',
fields: {
phoneId: {
type: 'number'
},
type: {
type: 'string',
editable: true
},
tel: {
type: 'string',
editable: true
},
typeId: {
type: 'number',
editable: true
}
}
}
}
},
autoBind: false,
columns: [
{
field: 'phoneId',
headerTemplate: '<b>Phone Id</b>',
filterable: false,
width: '50px',
hidden: true
},
{
field: 'type',
headerTemplate: '<b>Type</b>',
filterable: false,
editor: phoneTypeEditor,
width: '80px',
// template: '#=type#'
},
{
field: 'tel',
headerTemplate: '<b>Number</b>',
filterable: false,
}
],
edit: function(e) {
var ddl = e.container.find('[data-role=dropdownlist]').data('kendoDropDownList');
if (ddl) {
ddl.open();
}
},
height: '75',
filterable: true,
editable: true,
sortable: true,
scrollable: true
}).data("kendoGrid");
}
dataItem is a method so you should not use it as:
$('#contactPhonesGrid').data("kendoGrid").dataSource.dataItem
but as:
$('#contactPhonesGrid').data("kendoGrid").dataSource.dataItem(something here)
See documentation here : http://docs.telerik.com/kendo-ui/api/web/grid#methods-dataItem

Categories