I am trying to figure out within a Kendo UI template for a list view how to loop through a collection within each object to render the information on the page. Here is an example of the json I am playing with:
{"Data":[{"Title":"Malicious Acts","KeyPairs":{"Key1":"12","Key2":"24"}}, {"Title":"Enrollments","KeyPairs":{"Key1":"12","Key2":"24"}},{"Title":"Customer Feedback","KeyPairs":{"Key1":"12","Key2":"24"}},{"Title":"Questionable Accounts","KeyPairs":{"Key1":"12","Key2":"24"}}],"Total":4,"AggregateResults":null,"Errors":null}
I want to render the KeyPairs items in the template and just an having some trouble understanding how to.
Here is the source:
<div id="subscriberFunctions">
<script type="text/x-kendo-tmpl" id="template">
<div class="subscriberFunction">
<h3>${Title}</h3>
<!-- Display KeyPairs -->
</div>
</script>
@(Html.Kendo().ListView<SubscriberMenuFunction>()
.Name("listView")
.TagName("div")
.ClientTemplateId("template")
.DataSource(dataSource =>
{
dataSource.Read(read => read.Action("SubscriberMenu", "ListView"));
})
.Selectable(selectable => selectable.Mode(ListViewSelectionMode.Single))
)
</div>
I'm sure I'm just overthinking this, and it is something simplistic, but not sure how to implement the foreach loop in the template for Kendo UI to recognize it.
Thanks in advance!
You can do this with a counter in the for-loop. This should fix your issue:
<script type="text/x-kendo-tmpl" id="template">
<div class="subscriberFunction">
<h3>${Title}</h3>
<!-- Display KeyPairs -->
<ul>
#for (var i=0,len=KeyPairs.length; i<len; i++){#
<li>${ KeyPairs[i] }</li>
# } #
</ul>
</div>
</script>
You can have arbitrary JavaScript code inside a template:
<script type="text/x-kendo-tmpl" id="template">
<div class="subscriberFunction">
<h3>${Title}</h3>
<!-- Display KeyPairs -->
<ul>
# for (var key in KeyPairs) { #
<li>${ KeyPairs[key] }</li>
# } #
</ul>
</div>
</script>
It is possible to loop through the collection once you know the syntax. This is basically Stans answer with clearer syntax.
If you're using a List you can access properties just by adding them, e.g., <li>#=KeyPairs[i].FooBar#</li>
<script type="text/x-kendo-tmpl" id="template">
<div class="subscriberFunction">
<h3>#=Title#</h3>
<ul>
# for (var i = 0; i < KeyPairs.length; i++) { #
<li>#=KeyPairs[i]#</li>
# } #
</ul>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With