Looping through JSON objects in a Kendo JavaScript Template

1.3k views Asked by At

I am trying to figure out how I can create a Kendo template that will loop through a JSON array returned by an AJAX request. Here is what the data object look likes:

[{"Id":5, "CreatedBy":"testuser1"},
{"Id":6,"Archived":false,"CreatedBy":"testuser2"},
{"Id":7,"Archived":false,"CreatedBy":"testuser3"}]

I would like to list just the CreatedBy field like this in a Kendo template:

Users List:
testuser1
testuser2
testuser3

Here is my attempt and it is not working:

<ul>
     # for (var i = 0; i < data.length; i++) { #
          <li>#= data[i].CreatedBy #</li>
     # } #
</ul>

I just get a listing of undefined, undefined, undefined... and when I remove CreatedBy and just do data[i] I get each letter of each field listed. How do I access the actual CreatedBy values from the data object?

2

There are 2 answers

0
Blake Rivell On

I was able to accomplish what I wanted by parsing it first. If anyone else has a better cleaner way of doing it please let me know.

<script id="myKendoTemplate" type="text/x-kendo-template">
    <ul style="list-style: none; padding: 0;">
        # var objList = $.parseJSON(data); #
        # for (var i = 0; i < objList.length; i++) { #
            <li>#= objList[i].CreatedBy #</li>
       # } #
    </ul>
</script>

If anyone is interested another update is that I found this in the kendo window documentation. If you set dataType to json the data gets parsed by jQuery for you and you don't need the $.parseJSON(data) line.

0
shole On

As discussed, the problem is due to the dataType of the AJAX request.

By default the return data type is string, which cannot parsed by Kendo Template.

After explicitly specified the dataType: "json" in the request, or like OP's own answer which parse the return data to JSON type, it can be understood by Kendo Template and act normal again.