This is a migrated thread and some comments may be shown as answers.

Simple JSON databinding

19 Answers 4931 Views
Data Source
This is a migrated thread and some comments may be shown as answers.
Gavin Howlett-Foster
Top achievements
Rank 1
Gavin Howlett-Foster asked on 24 Apr 2012, 10:21 PM
Just starting out with Kendo and JSON and not having much luck in binding a grid to a json datasource. Here's my data, stored as a file called 'data.json' stored in the same directory as the page:

{
“firstName”: “John”,
“lastName”:”Smith”,
“department”:”Human Resources”
}

and my page:

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Kendo1.aspx.vb" Inherits="KendoUI.Kendo1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link href="Styles/kendo.common.min.css" rel="stylesheet" type="text/css" />
    <link href="Styles/kendo.default.min.css" rel="stylesheet" type="text/css" />
    <!--Then paste the following for Kendo UI Web scripts-->
    <script src="js/jquery.min.js" type="text/javascript"></script>
<script src="js/kendo.web.min.js" type="text/javascript"></script>
</head>
<body>
    <form id="form1" runat="server">
    <script type="text/javascript">
        $(document).ready(function () {

            var ds = new kendo.data.DataSource({
                transport: {
                    read: {
                        url: "data.JSON", dataType: "json"
                    }
                }
            });

            $("#grid").kendoGrid({
               dataSource: ds,
               columns: [
                    {
                        field: "firstName",
                        title: "First Name"
                    },
                    {
                        field: "lastName",
                        title: "Last Name"
                    }]
            });

        });

    </script>
    <div>
        <input id="myAutoComplete" />
    </div>
    <!-- Define the HTML div that will hold the Grid -->
    <div id="grid" style="width: 40%; margin: auto;">
    </div>
    </form>
</body>
</html>


Running the page just gives me the header row with the titles.

If anyone can point me in the right direction i'd be grateful.

Thanks

19 Answers, 1 is accepted

Sort by
0
Alexander Valchev
Telerik team
answered on 26 Apr 2012, 09:45 AM
Hi Gavin,

Your code looks OK, but it seems that your Json is invalid, because you are not using standard quotation marks (see attached screenshot). Another problem with your data file is that the dataSource expects collection of items and you are returning a single object.
Please try to run your page with the following Json:
[
    {
        "firstName": "John",
        "lastName": "Smith",
        "department": "Human Resources"
    }
]


Greetings,
Alexander Valchev
the Telerik team
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
0
Julien
Top achievements
Rank 1
answered on 30 Apr 2012, 07:36 PM
Hi, I'm trying to do the exactly same thing but for a chart with this json :

[{ "year": "1000", "sales": 20 },
 { "year": "1500", "sales": 10 },
 { "year": "1600", "sales": 15 }, 
 { "year": "2000", "sales": 60}] 

I included the json in my project with the name : kendo.json and there it's my code :


<html>
<head>


<title>Kendo Test</title>


<link href="Styles/kendo.dataviz.min.css" rel="stylesheet" type="text/css" />
<script src="Scripts/jquery.min.js" type="text/javascript"></script>
<script src="Scripts/kendo.dataviz.min.js" type="text/javascript"></script>


</head>


<body>

<div id="chart" style="width: 400px; height: 600px"></div>

<script type="text/javascript">

    var ds = new kendo.data.DataSource({
        transport: {
            read: "kendo.json",
            dataType: "json"                 
        }
    });


 $("#chart").kendoChart({
     dataSource: ds,
     series: [{
         field: "sales",
         name: "Sales"
     }],
   
     categoryAxis: {
         field: "year"
     }
 });
</script>
</body>

</html>


But it's not working, the attachment is a picture of what I get when I run the application. 

Please if someone could help me.
0
Chris
Top achievements
Rank 1
answered on 02 May 2012, 08:59 AM
Hi,

I am also having problems, I have tried many different configurations and have simplified it to the following:

$(document).ready(function () {
$("#grid").kendoGrid({
dataSource: {                      
transport: {
read: {
url: "http://api.domain.co.uk/Service.svc/Documents?Type=1",
dataType: "jsonp"
}
},
schema: { data: 'DocumentsResult' }                    
},
height: 250,                   
columns: [
{ field: "No" },
{ field: "Type" },
{ field: "SellToCustomerCode" }
]
});
});

Here is a copy of some of the data:

{"DocumentsResult":[{"No":1001,"SellToCustomerCode":"","Type":1},{"No":1002,"SellToCustomerCode":"","Type":1},{"No":1003,"SellToCustomerCode":"","Type":1},{"No":1004,"SellToCustomerCode":"","Type":1},{"No":1005,"SellToCustomerCode":"","Type":1},{"No":1006,"SellToCustomerCode":"","Type":1},{"No":1007,"SellToCustomerCode":"","Type":1},{"No":1008,"SellToCustomerCode":"","Type":1},{"No":1009,"SellToCustomerCode":"","Type":1},{"No":1010,"SellToCustomerCode":"","Type":1}]}

I have tried it with and without a wrapper (DocumentsResult) and I've tried using json as the dataType value and nothing seems to work.

Thanks in advance.
0
Alexander Valchev
Telerik team
answered on 03 May 2012, 08:58 AM
Hi guys,

@Julien
The dataType configuration is part of the read object, not the transport itself. I have tried to run your code with this change and everything seems to work as expected. Please check my example and let me know if I missed something.

@Chris
Jsonp is different from Json, so if you are using Json data you have to set the dataType: "json". Apart from that I do not see any other problems with your code. I tested it in this jsFiddle page using the echo service to simulate Ajax request.

Regards,
Alexander Valchev
the Telerik team
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
0
Chris
Top achievements
Rank 1
answered on 03 May 2012, 09:30 AM
Hi Alexander,

Thank you for your response; I've checked your jsFiddle page and it does indeed appear to work there, however, whenever I put my url in, it doesn't work.  I've used Fiddler to check the response from my web service to ensure that it is in fact outputting correctly and I believe it is.  I've included the raw response so you can see if I am missing anything:

HTTP/1.1 200 OK
Content-Length: 183
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/7.5
X-Powered-By: ASP.NET
Date: Thu, 03 May 2012 08:14:55 GMT


{"DocumentsResult":[{"No":101005,"SellToCustomerCode":"30000","Type":1},{"No":101009,"SellToCustomerCode":"38128456","Type":1},{"No":101011,"SellToCustomerCode":"43687129","Type":1}]}

"Jsonp is different from Json":
I'm sure I read somewhere else in the forum that jsonp should be used if you are calling a service on another domain?  Perhaps I misread but that was why I was using jsonp, but like I said in my initial post; I had already tried json and that did not work.  I've tried changing my code back to json again and still it does not work.  Just to add a bit of extra clarification here though; my web-site is on www.domain.co.uk and from there I am calling a web-service at api.domain.co.uk.

Regards,

Chris
0
Safak
Top achievements
Rank 1
answered on 03 May 2012, 11:20 AM
Hi ,I am having databinding problem . When I run these codes , I get nothing ...I really dont know whats wrong ?Can you please help me ? ?here json file :  
[
    {
        "country": "Spain",
        "year": "2008",
        "unit": "GWh",
        "solar": 2578,
        "hydro": 26112,
        "wind": 32203,
        "nuclear": 58973
    },
    {
        "country": "Spain",
        "year": "2007",
        "unit": "GWh",
        "solar": 508,
        "hydro": 30522,
        "wind": 27568,
        "nuclear": 55103
    },
    {
        "country": "Spain",
        "year": "2006",
        "unit": "GWh",
        "solar": 119,
        "hydro": 29831,
        "wind": 23297,
        "nuclear": 60126
    },
    {
        "country": "Spain",
        "year": "2005",
        "unit": "GWh",
        "solar": 41,
        "hydro": 23025,
        "wind": 21176,
        "nuclear": 57539
    }
     
]


  




HERE MY HTML FILE :

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="source/kendo.all.js"></script>
    <link href="styles/kendo.common.css" rel="stylesheet" />
    <link href="styles/kendo.default.css" rel="stylesheet" />
</head>
<body>  
        <div id="example" class="k-content">
            <div class="chart-wrapper">
                <div id="chart"></div>
            </div>
            <script>
                var dataSource = new kendo.data.DataSource({
                transport: {
                read: "spain-electricity.json"
                           }
 
                function createChart()
                {
                    $("#chart").kendoChart({
                           dataSource: dataSource,
                           series: [{
                           field: "wind"
                                   }],
                          categoryAxis: {
                              field: "year"
                                }
                }
 
                $(document).ready(function() {
                    setTimeout(function() {
                        // Initialize the chart with a delay to make sure
                        // the initial animation is visible
                        createChart();
 
                        $("#example").bind("kendo:skinChange", function(e) {
                            createChart();
                        });
                    }, 400);
                });
            </script>
        </div>
 
 
</body>
</html>


THANKS
0
Chris
Top achievements
Rank 1
answered on 03 May 2012, 11:47 AM
Hi Alexander,

Finally got this working, and the difficulty was the fact that this was cross-domain, once I understood that I started investigating WCF, JSON and cross-domain issues.

For anyone else that may come across this issue, particularly those that have their web-service on a different sub-domain like we have, you need to ensure that your web-service is set up to respond correctly to a jsonp call, since they are in fact different from a straight json call.  In my example I was calling "http://api.domain.co.uk/service.svc/documents?type=1" but when you make a request using jsonp it adds "&callback=jQuery<some random numbers>" to the end of the url.  Your web-service is not generally set up to do anything with this extra parameter and so ignores it and responds the same way it would without it.  That's the problem, I didn't see this extra bit when I was looking at Fiddler, and since the response from the web-server was responding exactly the way I thought it should (returning the data correctly) I didn't think anything was wrong that end.  It is only when you understand how jsonp works, do you know that you need to configure the server to respond differently.

So all you need to do is simply change to the bindings section of your web.config file on the web-server to be something like:
<bindings>
<webHttpBinding>
<binding crossDomainScriptAccessEnabled="true" />
</webHttpBinding>
</bindings>

I'm using webHttpBindings, but you could be using something different I think.

This property is a little bit misleading I think because it would already reply cross domain, with or without this, but adding this property simply made the web-service properly format and wrap a JSONP request with a function based on the "callback" parameter in the URL.  Of course, I understand that I am only making a request from a different "sub-domain" and not having this property may result in a denied response if the request was make from a completely different domain, but that is not what I need so I haven't tested that.

Anyway, I hope this explanation is clear and thorough enough to help someone else out in future.  Please reply if you have any further questions and I'll do my best to help.
0
Julien
Top achievements
Rank 1
answered on 03 May 2012, 05:07 PM
Thank you Alexander it's working now !.

Problem Solved :)
0
Alexander Valchev
Telerik team
answered on 04 May 2012, 10:19 AM
Hello guys,

@Safak
It seems that jQuery is not included in your page, please have in mind that KendoUI depends on jQuery and does not work without it.
<head>
    <title></title>
    <!-- JQuery must be included before kendo.js files -->
    <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
    <script src="source/kendo.all.js"></script>
    <link href="styles/kendo.common.css" rel="stylesheet" />
    <link href="styles/kendo.default.css" rel="stylesheet" />
</head>

You could read more about JavaScript dependencies in the corresponding documentation.

@Chris
Thank you for sharing your solution, I am sure it will help to the users that experience similar issues.

@Julien
I am glad to hear that the problem is solved.

Greetings,
Alexander Valchev
the Telerik team
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
0
David Larew
Top achievements
Rank 1
answered on 17 May 2013, 02:49 AM
I'm looking for a working sample that pulls from an external json file.
Thanks,
David
0
Greg
Top achievements
Rank 1
answered on 26 Oct 2013, 09:38 PM
Hi,

I have a WCF service returning JSON data serialized by JavaScriptSerializer().Serialize().

The data is returned in the following format:

"[{\"PlayerID\":1,\"FirstName\":\"Tiger\",\"LastName\":\"Woods\",\"Score\":-10},{\"PlayerID\":2,\"FirstName\":\"Adam\",\"LastName\":\"Scott\",\"Score\":-9},{\"PlayerID\":3,\"FirstName\":\"Phil\",\"LastName\":\"Mickelson\",\"Score\":-9},{\"PlayerID\":4,\"FirstName\":\"Henrik\",\"LastName\":\"Stenson\",\"Score\":-8},{\"PlayerID\":5,\"FirstName\":\"Justin\",\"LastName\":\"Rose\",\"Score\":-7},{\"PlayerID\":6,\"FirstName\":\"Rory\",\"LastName\":\"McIlroy\",\"Score\":-6}]"

I am binding the data to a kendoGrid, the data does not show.  Isn’t the above a correct JSON format?

Thanks,

Greg.
0
Greg
Top achievements
Rank 1
answered on 27 Oct 2013, 02:22 AM
Ok, I found a solution:

The service needs to return a Stream instead of a string.


string jsonString = new JavaScriptSerializer().Serialize( leaders );
return ( new MemoryStream( Encoding.UTF8.GetBytes( jsonString ) ) );


Regards,

Greg.

0
Sean
Top achievements
Rank 1
answered on 14 Nov 2013, 02:20 PM
Greg, 
I believe I'm going to try the same as well. This is what I'm seeing from my endpoint:
{"StreetsInTown":"[{\"Street\":\"ABBIE RD\"},{\"Street\":\"ABBOTTS LN\"},{\"Street\":\"ACETO ST\"},{\"Street\":\"ACORN RD\"},{\"Street\":\"ZUWALLACK LN\"}]"
Not sure if I need to do a JSON.parse or tweak the endpoint...

Thanks
0
Alexander Valchev
Telerik team
answered on 14 Nov 2013, 02:38 PM
Hello Todd,

This is a common mistake that many developers do - the JSON format is incorrect.  The data array should be an array of objects (key-value pairs), currently you are returning a string:
{"StreetsInTown":"[{\"Street\":\"ABBIE RD\"}]"}

Instead it should look like:
{"StreetsInTown": [{"Street":"ABBIE RD"}] }

In addition you should set the schema.data to "StreetsInTown".

Regards,
Alexander Valchev
Telerik
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
0
Sean
Top achievements
Rank 1
answered on 14 Nov 2013, 02:51 PM
Thanks. I'm guessing it's the string I'm creating. This is how I'm creating my data via my REST endpoint. Do you have a suggestion on how I could tweak it for easier consumption with the Kendo dataSource/controls? Here is how I'm doing it:
private byte[] GetAddressQueryHandler(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties)
        {
            responseProperties = null;
            _sqlselect = null;
  
            string townNameVal;
            string streetNameVal;
            string streetNumVal;
              
            JsonObject result = new JsonObject();          
              
            bool found = operationInput.TryGetString("townName", out townNameVal);
            if (!found || string.IsNullOrEmpty(townNameVal))
                throw new ArgumentNullException("townName");
  
            // get all street names in town X
            _sqlselect = "SELECT DISTINCT Street FROM Customers WHERE Town = '" + townNameVal + "' Order by Street";
  
            DataTable streetsFromTownTable = GetDataTableCustTableSchema();
            String jsonStringStreetsFromTown = ConvertDataTableToJSONString(streetsFromTownTable);
            result.AddString("StreetsInTown", jsonStringStreetsFromTown);
  
            found = operationInput.TryGetString("streetName", out streetNameVal);
            if (!found || string.IsNullOrEmpty(streetNameVal))              
                return Encoding.UTF8.GetBytes(result.ToJson());
  
            // get all streets in town X with name X
            _sqlselect = "SELECT Street_Num FROM Customers WHERE Town = '" + townNameVal + "' AND Street = '" + streetNameVal + "' Order by Street_Num";
  
            DataTable streetNumsOnStreetTable = GetDataTableCustTableSchema();
            String jsonStringstreetNumsOnStreet = ConvertDataTableToJSONString(streetNumsOnStreetTable);
            result.AddString("StreetNumsOnStreet", jsonStringstreetNumsOnStreet);
  
            found = operationInput.TryGetString("streetNum", out streetNumVal);
            if (!found || string.IsNullOrEmpty(streetNumVal))              
                return Encoding.UTF8.GetBytes(result.ToJson());
  
            // get all streets in town X with name X and Street_Num X
            _sqlselect = "SELECT * FROM Customers WHERE Town = '" + townNameVal + "' AND Street = '" + streetNameVal + "' AND Street_Num = " + streetNumVal;
  
            DataTable streetAddressTable = GetDataTableCustTableSchema();
            String jsonStringStreetAddress = ConvertDataTableToJSONString(streetAddressTable);
            result.AddString("StreetAddress", jsonStringStreetAddress);
                          
            return Encoding.UTF8.GetBytes(result.ToJson());
        }
  
 public DataTable GetDataTableCustTableSchema()
        {          
            DataTable dataTable = new DataTable();
            using (SqlConnection conn = new SqlConnection("Server=xxx;Database=xxx;Trusted_Connection=True"))
            {
                using (SqlCommand cmd = new SqlCommand(_sqlselect, conn))             
                {
                    conn.Open();
                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        dataTable.Load(reader);
                    }
                }              
            }
            return dataTable;
        }
  
public String ConvertDataTableToJSONString(DataTable dataTable)
        {
            JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
  
            List<Dictionary<String,System.Object>> tableRows = new List<Dictionary<String, System.Object>>();
  
            Dictionary<String,System.Object> row;
  
            foreach (DataRow dr in dataTable.Rows)
            {
                row = new Dictionary<String, System.Object>();
                foreach (DataColumn col in dataTable.Columns)
                {
                    row.Add(col.ColumnName, dr[col]);
                }
                tableRows.Add(row);
            }
            return serializer.Serialize(tableRows);
        }
0
Neal
Top achievements
Rank 1
answered on 14 Nov 2013, 10:10 PM
Hi - I know this is an old post, but thanks for putting up the JSFiddle.  I was able to get JSON data binding to my grid easily after seeing it.  They should add that fiddle to the documentation!
0
Sean
Top achievements
Rank 1
answered on 14 Nov 2013, 11:02 PM
Alexander,

I'm very close to having this figured out. With my changes I'm getting a response back, undefined, but the data is showing up (proper json string format) in the reply.

I'm thinking I need a JSON.parse somewhere to display the data in the dropdown?

$("#cboSearchString2DDL").kendoDropDownList({
    dataTextField: "Street",
    dataValueField: "Street",
    autoBind: false,
    dataSource: {
        transport: {
            read: {
                url: _urlSOESearchAddress + "townName=Branford&f=json", // TODO: add DDL1 value
                //contentType: "application/json; charset=utf-8",
                dataType: "json",
                type: "GET" //"POST"
            },
            success: function (msg) {
                options.success($.parseJSON(msg.StreetsInTown))
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            }
        },
        schema: {
            data: "StreetsInTown"
        }
    }
});
Thanks!
0
Gustavo
Top achievements
Rank 1
answered on 21 Dec 2017, 10:03 PM
You saved my life!!!!
0
Van Thao
Top achievements
Rank 1
Iron
answered on 02 May 2022, 02:02 PM | edited on 02 May 2022, 06:15 PM

HI, I am new to Web Development (Ruby on Rails) and also new to Kendo UI. I am having similar problem with JSON binding on the KendoUI Grid. Please help.

This is the Ruby Controller:

class PatientsController < ApplicationController
def index
@patients = Patient.all
end


I am building the JSON file from @patients.

<div id="grid"></div>
<% File.open("patients.json","w") do |f| %>
<% f.write(@patients.as_json) %>
<% end %>
<%= file = File.read('patients.json') %>


The file looks like this:

[{"id"=>1, "name"=>"Dianna Ross", "doveegene"=>true, "ramq"=>"ROSD67182202", "np"=>true, "created_at"=>"2022-04-12T14:43:35.513Z", "updated_at"=>"2022-04-12T14:52:25.516Z", "date_visit"=>nil}, {"id"=>2, "name"=>"David Copperfield", "doveegene"=>true, "ramq"=>"COPD87191510", "np"=>true, "created_at"=>"2022-04-12T18:29:11.772Z", "updated_at"=>"2022-04-12T18:29:11.772Z", "date_visit"=>nil}, {"id"=>3, "name"=>"David Edwards", "doveegene"=>false, "ramq"=>"EDWD77108803", "np"=>true, "created_at"=>"2022-04-12T18:54:24.373Z", "updated_at"=>"2022-04-12T18:54:24.373Z", "date_visit"=>nil}, {"id"=>4, "name"=>"", "doveegene"=>nil, "ramq"=>"", "np"=>nil, "created_at"=>"2022-04-21T15:28:50.418Z", "updated_at"=>"2022-04-21T15:28:50.418Z", "date_visit"=>nil}]



Here is the script:

<script>

    $(document).ready(function(){
        $("#grid").kendoGrid({
            columns: [{
                field: "name",
                title: "Name"
            },
            {
                field: "doveegene",
                title: "DOvEEgene"
            },
            {
                field: "ramq",
                title: "RAMQ"
            },
            {
                field: "date_visit",
                title: "Date"
            },
            {
                field: "np",
                title: "New Patient"
            }],
            dataSource: {
              transport: {
                read: {
                  url: "patients.json"
              },
              schema: {
                data: "data"
              }
            }}
        });
    });

</script>

The result:
- I only got the header and nothing binding.

- In Chrome Dev Tools Console, I got:

GET http://localhost:3000/patients.json 406 (Not Acceptable)

In the Terminal, rails server shows:

ActionController::UnknownFormat (PatientsController#index is missing a template for this request format and variant.

request.formats: ["application/json"]
request.variant: []):
 
actionpack (6.1.5) lib/action_controller/metal/implicit_render.rb:42:in `default_render'
actionpack (6.1.5) lib/action_controller/metal/basic_implicit_render.rb:6:in `block in send_action'
<internal:kernel>:90:in `tap'...

I have been struggling for a week.
I would appreciate your help.
Thank you,

Van

Neli
Telerik team
commented on 05 May 2022, 09:53 AM

Tags
Data Source
Asked by
Gavin Howlett-Foster
Top achievements
Rank 1
Answers by
Alexander Valchev
Telerik team
Julien
Top achievements
Rank 1
Chris
Top achievements
Rank 1
Safak
Top achievements
Rank 1
David Larew
Top achievements
Rank 1
Greg
Top achievements
Rank 1
Sean
Top achievements
Rank 1
Neal
Top achievements
Rank 1
Gustavo
Top achievements
Rank 1
Van Thao
Top achievements
Rank 1
Iron
Share this question
or