How to read kendo grid columns from a json file - json

I have a kendo grid which is reading data from a remote json file. I want that the grid columns should also be read from the same json file so that I dont have to change the client side code again and again. Whatever comes in the json file it should be capable enough to present the same data without any hard coding on client side. My json file looks like
{ "data":[
{"_type":"ProductDetails:#NWProducts","Discount":0,"OrderId":10248,"ProductId":11,"UnitPrice":14.0000,"quanity":12},{"_type":"ProductDetails:#NWProducts","Discount":0,"OrderId":10248,"ProductId":42,"UnitPrice":9.8000,"quanity":10},{"_type":"ProductDetails:#NWProducts","Discount":0,"OrderId":10248,"ProductId":72,"UnitPrice":34.8000,"quanity":5},{"_type":"ProductDetails:#NWProducts","Discount":0,"OrderId":10249,"ProductId":14,"UnitPrice":18.6000,"quanity":9}],
"columns":[
{"field":"_type","title":"Type"},{"field":"Discount","title":"Discount($)"},{"field":"OrderId","title":"Order ID"},{"field":"ProductId","title":"Product ID"},{"field":"UnitPrice","title":"Unit Price"},{"field":"quanity","title":"Quanity"}]
}
HTML code is as below
<div id="grid"></div>
JS code is below
$("#grid").kendoGrid({
title: { text: "Stats" },
sortable: false,
pageable: {
pageSizes: true,
buttonCount: 5
},
columnMenu: true,
dataSource: {
transport: {
read: {
url: "............/demo.json",
dataType: "json"
}
},
schema: {
data: "data"
}
},
columns: {
//What should be done here.
}
});
I tried the same transport read schema way to fetch the column data but it did not work. If I store the same columns json data in a variable and substitute that variable for columns then it works. Is there any way to store the columns json data as such in a variable from the json file. What is the best approach to achieve this behavior. Any help would be appreciated.
Thanks in Advance.

Related

How can I use AJAX with web methods to send JSON objects to a jQuery DataTable using asp.net?

So I have the jQuery datatable using AJAX to call for the JSON in this format.
$(document).ready(function () {
$('#test').DataTable({
ajax:{
url:"players.json",
dataSrc:""
},
columns: [
{data: "id"},
{ data: "player" },
{ data: "points" },
{ data: "steals" },
{ data: "blocks" },
{ data: "assists" },
{ data: "MPG" },
{ data: "shot %" },
{ data: "3 %" }
]
});
});
My aspx.cs file has a method to create the JSON file which works.
[System.Web.Services.WebMethod]
public static void loadTable()
{
NBAPlayerRepository players = new NBAPlayerRepository();
DataTable dt = players.GetAll();
var json = dt.ToJson();
System.IO.File.WriteAllText(#"C:\Users\wheres\Downloads\nbaStats\nbaStats\nbaStats\players.json", json);
}
And the JSON looks like this:
[{"id" : "67926aa7-46b7-4418-96db-fc7e5216aac4","playername" : "Wilson Heres","points" : "34534","steals" : "34","blocks" : "34","assists" : "343","mpg" : "343","shootingpercentage" : "33.3429985046387","threepointpercentage" : "33.3429985046387"}
,{"id" : "6dc42e0b-8750-463d-a9ef-5a025a27154b","playername" : "Wilson Heres","points" : "34534","steals" : "34","blocks" : "34","assists" : "343","mpg" : "343","shootingpercentage" : "33.3429985046387","threepointpercentage" : "343.334014892578"}
,{"id" : "f727130c-5b94-4730-a653-cfb603c73b8a","playername" : "Wilson Heres","points" : "34534","steals" : "34","blocks" : "34","assists" : "343","mpg" : "343","shootingpercentage" : "33.3429985046387","threepointpercentage" : "343.334014892578"}
]
But now I am getting this error "jquery.dataTables.min.js:48 Uncaught TypeError: Cannot read property 'length' of undefined"
Edit: This all works now. Just had to add dataSrc:""
Cleaned-up version of your DataTables initialization
$(document).ready(function () {
$('#test').DataTable({
ajax: {
url: "players.aspx/loadTable"
},
columns: [
{ data: "id" },
{ data: "player" },
{ data: "points" },
{ data: "steals" },
{ data: "blocks" },
{ data: "assists" },
{ data: "MPG" },
{ data: "Shot %" },
{ data: "3 %" },
]
});
});
This may seem like a lot of stuff was removed from your code, so let me make some explanations/assumptions about what was changed.
Assumptions
First, an assumption: DataTables will always try to use a GET request, not a POST when first getting the data from the table, so make sure that your data processing code expects that.
I also am assuming that you have no strong desire to have your Ajax separate from your initialization and that was just how you decided to do it as a first attempt. If that is the case, let me know and I'll update the code to match that.
Explanation
Your formatting is incorrect in some areas and against DataTables standard in others, so this version should do most of what you were trying to do in a much simpler form. A lot of your Ajax options are unnecessary because they are already the default (JSON for the data type, for example), which is why they have been removed.
One nice thing about DataTables is that you can have the Ajax options in the initialization, which is what I have done here. You do lose the success and failure callbacks but I think that for debugging purposes they aren't really necessary and having any extra code increases the amount of stuff to debug (I don't even use those callbacks in most of my final code).
Most of the other changes were mainly incorrect nomenclature (e.g. data instead of title in the column definitions.
Disclaimer
While I would recommend these changes in general just to improve your code, I would make sure to take a look at the format of the JSON that is being sent to and from the server. If you don't know how to do that I'd recommend downloading Fiddler to 'listen in' on the JSON data being sent.
If your JSON is wrong, no amount of changes to the page are going to make the table appear.
Finally, make sure you have no JS errors on the page. Use your browser's developer console (F12) to check that.
If you do find any JS errors, post them in your question. I'd also recommend posting the JSON data being sent to the question as well so that we can ensure the format is correct.

Kendo UI Treeview doesn't display date correctly

I am trying to display my json from a mvc controller to be displayed on a checkboxed kendo ui treeview. The code on the asp.net mvc view and the json sent to the view are given below
MyDoc.cshtml code
<script>
$("#treeview").kendoTreeView({
checkboxes: {
checkChildren: true,
},
dataSource: {
//type: "odata",
transport: {
read: {
url: '#Url.Content("~/Document/GetMyDocs")',
type: "post",
dataType: "json"
}
},
schema: {
model: {
id: "id", text:"Name",
children: "Files"
}
}
},
dataTextField: [ "Name"],
check: onCheck
});
json object
[{"id":1,"Name":"Checking",
"Files":[{"Filename":"doc10","id":"1afd5a4f-086f-44d2-9287-8098384e379e"},
{"Filename":"doc11","id":"89ea3366-14b8-4e91-8273-6e2a51fbe516"}]},
{"id":2,"Name":"Saving",
"Files":[{"Filename":"doc20","id":"c7a88f5d-067e-4f20-93b6-da6eff69d532"},
{"Filename":"doc21","id":"8a0a62ed-1b4a-4e5e-8d59-d57a975a7ab0"}]}]
When I view the page only the toplevel text, "Checking" and "Saving" shows. The date present under Files comes out as undefined.
Thanks
It looks like that Kendo UI uses the dataTextField: [ "Name"] for both the parent and the child node. Since the json in the child data doesn't have a field name equal to "Name" it came out as undefined. Once I changed the property, "FileName" into "Name", it worked. The Telerik's documentation is as atrocious as other third party controls. All their demos are more geared to show how easy peasy it is to create a sexy looking UI using few hard coded data than showing how to create a real world application!

Simple JSON issue with kendo-grid

Was wondering if you could help me, I've been battling with trying to get my rest JSON data to display correctly in a kendo-grid for a few hours now, and have just worked out it's due to additional nodes on my JSON
$(function() {
var grid = $("#grid").kendoGrid({
dataSource: {
data: {
"ttPortalCommunicationResult": [{
"UniqueID": 7,
"DocumentTitle": "Expense Contribution Scheme Guide",
"ActivationDate": "2012-05-22",
"DeactivationDate": "2020-05-12",
"CategoryDesc": "Operational news"
}],
},
pageSize: 10,
schema: {
data: "ttPortalCommunicationResult"
}
}
}).data("kendoGrid");
});
I get an error Cannot read property 'slice' of undefined.
My question is how can I use only the "ttPortalCommunicationResult" node on JSON data which contains the additional nodes?
I would have assumed kendo would understand how to traverse to that node. An explanation why it can't would also be nice.
Use dataSource schema parse method
schema: {
parse : function(data) {
return data.ttPortalCommunicationResult;
}
}

Placing JSON response elements into a store- Ext JS

I'm wondering what the best way would be to load elements of a JSON response into a store.
What I have:
jQuery ajax request
var foodRequest = $.ajax({
url: "MyServlet",
type: "post",
cache: false,
dataType: "json",
data: JSON.stringify(searchquery),
error : function() {
alert ('ERROR!! Please re-enter the search criteria and try again.');
}
});
ajax response
{
"Foods":[
{
"Food":{
"name":"Spaghetti",
"id":"001",
"attributes":[
{
"attrname":"Price",
"attrvalue":"18.99"
},
{
"attrname":"Description",
"attrvalue":"Spaghetti is delicious, don't argue with me"
},
etc...
What I want:
(each element has 4 attributes)
var grid = Ext.define('Myapp.view.Grid' ,{
extend: 'Ext.grid.Panel',
id: 'mygrid',',
initComponent: function(columns) {
this.columns = [
{header: 'attrname', dataIndex: 'attrvalue', flex: 2 },
{header: 'attrname', dataIndex: 'attrvalue', flex: 2 },
{header: 'attrname', dataIndex: 'attrvalue', flex: 2 },
{header: 'attrname', dataIndex: 'attrvalue', flex: 2 },
etc...
How can I take the attributes from the json response and place them into a store my grid can use, as seen above?
Cheers!
The data you are returning looks like a tree. A normal grid works with fixed columns. In short:
a grid uses a store
the Store uses a number of fields or a Model.
a grid has a number of predefined columns, each column references a store(model) field by means of a dataIndex.
Now when the store loads data (either through a proxy or by manually dumping records in it). it creates a record internally. The fields on the record that are available are the fields you defined on the store or the fields you defined on the model the store uses.
Long story short, the normal setup of a grid and store is with a fixed number of columns and fields. In your case it would probably be better to use a TreePanel and store. Look at the treepanel example for this.
http://docs.sencha.com/extjs/4.0.7/extjs-build/examples/tree/treegrid.html
Good luck

Have jqGrid display raw json in a column

I have a use case where I would like to have jqGrid display some raw JSON for a particular column. I have the following JSON being sent from the server:
{"items":[
{
"code":"ABC123",
"description":"",
"custom_data":{"items":[
{"prop1":"val1","prop2":"val2"},
{"prop1":"val3","prop2":"val4"}
]}
},
{"code":"ABC124","description":"","custom_data":[]},
...,
]}
and a jqGrid configuration like so:
{
url:'/api/somewhere',
datatype: "json",
jsonReader : {
root:"items",
repeatitems: false,
id: "code"
},
colNames:['Code',
'Description',
'Data',],
colModel:[
{
name:'code', index:'code', width:100, hidden:false,
edittype:'text',
editable: true,
editrules:{required:true, edithidden:true},
editoptions: {readonly:false}
},
{
name:'description',
index:'description',
width:250,
editable:true,
edittype:'text',
editrules:{required:true}
},
{
name:'custom_data',
index:'custom_data',
width:100,
hidden:true,
sortable:false,
editable:true,
edittype:'text',
editrules:{required:false, edithidden:true}
},
],
...,
The grid displays OK, but the custom_data column is displayed as [object Object]. What I need is for it to display the raw JSON string I have tried calling JSON.stringify on the custom_data object for each row object using the loadComplete event, but that didn't work. I need to do some data manipulation after the GET anyway, as I want to delete null values from the custom_data object.
My users are comfortable reading and editing raw JSON, so I also need the add/edit form to accept raw JSON which will then get POSTed.
I'm not sure if I'm simply using the wrong event to convert the object back to a string, or if there is something else going on.
What you can do is usage of custom formatter for "custom_data" column
formatter: function (cellValue, options, rawData) {
return cellValue.items ? JSON.stringify(cellValue.items) : "";
}
I changed in the demo hidden property for "custom_data" column to true to see the data
Additionally you can consider to use userdata instead of hidden column to save additional custom data. I recommend you to read the answer additionally which shows not only how to use userdata, but additionally how to show additional data in form subgrid.