Simple JSON databinding

19 posts, 0 answers
  1. Gavin Howlett-Foster
    Gavin Howlett-Foster avatar
    1 posts
    Member since:
    Apr 2009

    Posted 24 Apr 2012 Link to this post

    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
  2. Alexander Valchev
    Admin
    Alexander Valchev avatar
    2890 posts

    Posted 26 Apr 2012 Link to this post

    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!
  3. Julien
    Julien avatar
    5 posts
    Member since:
    Apr 2012

    Posted 30 Apr 2012 Link to this post

    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.
  4. Chris
    Chris avatar
    25 posts
    Member since:
    Apr 2011

    Posted 02 May 2012 Link to this post

    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.
  5. Alexander Valchev
    Admin
    Alexander Valchev avatar
    2890 posts

    Posted 03 May 2012 Link to this post

    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!
  6. Chris
    Chris avatar
    25 posts
    Member since:
    Apr 2011

    Posted 03 May 2012 Link to this post

    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
  7. Safak
    Safak avatar
    5 posts
    Member since:
    Jun 2012

    Posted 03 May 2012 Link to this post

    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
  8. Chris
    Chris avatar
    25 posts
    Member since:
    Apr 2011

    Posted 03 May 2012 Link to this post

    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.
  9. Julien
    Julien avatar
    5 posts
    Member since:
    Apr 2012

    Posted 03 May 2012 Link to this post

    Thank you Alexander it's working now !.

    Problem Solved :)
  10. Alexander Valchev
    Admin
    Alexander Valchev avatar
    2890 posts

    Posted 04 May 2012 Link to this post

    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!
  11. David Larew
    David Larew avatar
    7 posts
    Member since:
    May 2010

    Posted 16 May 2013 Link to this post

    I'm looking for a working sample that pulls from an external json file.
    Thanks,
    David
  12. Greg
    Greg avatar
    4 posts
    Member since:
    Aug 2011

    Posted 26 Oct 2013 Link to this post

    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.
  13. Greg
    Greg avatar
    4 posts
    Member since:
    Aug 2011

    Posted 26 Oct 2013 Link to this post

    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.

  14. Sean
    Sean avatar
    15 posts
    Member since:
    Sep 2013

    Posted 14 Nov 2013 Link to this post

    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
  15. Alexander Valchev
    Admin
    Alexander Valchev avatar
    2890 posts

    Posted 14 Nov 2013 Link to this post

    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!
  16. Sean
    Sean avatar
    15 posts
    Member since:
    Sep 2013

    Posted 14 Nov 2013 Link to this post

    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);
            }
  17. Neal
    Neal avatar
    1 posts
    Member since:
    Nov 2013

    Posted 14 Nov 2013 Link to this post

    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!
  18. Sean
    Sean avatar
    15 posts
    Member since:
    Sep 2013

    Posted 14 Nov 2013 Link to this post

    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!
  19. Gustavo
    Gustavo avatar
    3 posts
    Member since:
    Jan 2011

    Posted 21 Dec 2017 in reply to Greg Link to this post

    You saved my life!!!!
Back to Top