Reputation: 328
I am a totally new to stackoverflow and knockout and I have a question. I would like to access an JSON object by index. It works fine if I add dummy data in my code, but it gives me an error if I add data from JSON and stops.
Error Uncaught TypeError: Unable to process binding "text: function (){return Ads()[0].AdContent }" Message: Cannot read property 'AdContent' of undefined
My ViewModel:
function AdListModel () {
var self = this;
self.Ads = ko.observableArray([]);
$.ajax({
type: "GET",
url: '/Home/GetAllAds',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
self.Ads(data);
},
error: function (err) {
alert(err.status + " : " + err.statusText);
}
});
}
ko.applyBindings(new AdListModel());
JSON I receive
[{"AdId":6,"AdContent":"sadasdasdsad","CategoryId":1,"CategoryNameRU":"Дом, стройка, ремонт"},{"AdId":12,"AdContent":"asdasd","CategoryId":1,"CategoryNameRU":"Дом, стройка, ремонт"}]
My HTML
<div data-bind="text: Ads()[0].AdContent"></div>
<div data-bind="foreach: Ads">
<p data-bind="text: AdId"></p>
<p data-bind="text: AdContent"></p>
<p data-bind="text: CategoryId"></p>
<p data-bind="text: CategoryNameRU"></p>
</div>
So, basically I would like to read just one property in JSON object with index 0 and then display all array.
Upvotes: 2
Views: 91
Reputation: 7641
The "Ads" array is empty until you don't get response on the ajax call. Hence "Ads()[0]" is undefined.
You can use additional check in the binding:
<!-- ko if: Ads().length > 0 -->
<div data-bind="text: Ads()[0].AdContent"></div>
<!-- /ko -->
Note: "foreach" binding processes empty arrays correctly.
Upvotes: 1