How to use kendo datasource when a REST service returns only one element

3 posts, 1 answers
  1. pedro
    pedro avatar
    4 posts
    Member since:
    May 2009

    Posted 07 Feb 2013 Link to this post

    I have a service (ASP.NET WebApi) whose URL returns a single object:

    http://localhost:60000/api/approvals/90a11073-cbfe-4442-9330-9b94d83d53a2

    But I can't get the datasource to handle the scenario. The request is made and the response is ok but in the change event I don't have any data. the ok from qunit fails.

    datasource.bind("change", function (e)
        {
            var element = datasource.get('90a11073-cbfe-4442-9330-9b94d83d53a2')
            ok(element);
            start();
        });

    Also inspecting e.sender.data() shows that there are no elements in the result!

    Is this supported? How?

    Thanks,
    Pedro

  2. Answer
    Atanas Korchev
    Admin
    Atanas Korchev avatar
    8462 posts

    Posted 07 Feb 2013 Link to this post

    Hi Pedro,

     The Kendo DataSource works with arrays. If your service returns a single element you need to convert it to array with one item. This is done by specifying the schema.data setting as a function:

    schema: {
        data: function(response) {
         return [response]; // create an array from the response
        }
    }


    I hope this helps,
    Atanas Korchev
    the Telerik team
    Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
  3. Kendo UI is VS 2017 Ready
  4. pedro
    pedro avatar
    4 posts
    Member since:
    May 2009

    Posted 07 Feb 2013 Link to this post

    For reference here goes my solution:

    // set the id of the model to the property named "id"
    self.DefaultItem = kendo.data.Model.define({
            id: "id"
        });
     
    self.dataSource = new kendo.data.DataSource({
            transport: {
                read: {
                    url: self.serviceAddress
                }
            },
            schema: {
                model: self.DefaultItem,
                data: function (result) {
                    if ($.isArray(result)) {
                        return result;
                    }
                    else {
                        return [result];
                    }
                }
            },
    // ... remaining datasource options

    Rgds,
    Pedro
Back to Top