Reputation: 328
Can anybody explain what's wrong in my code, I am new to knockout... So, initially I receive json data from database and it works. Than when I click 'Add some' I want to add(push) same data from database to my observable array. The code below obviously doesn't work. Thanks. Error: Unable to process binding "text: function (){return AdId }"...
HTML:
<div data-bind="foreach: Ads">
<p data-bind="text: AdId"></p>
</div>
<div data-bind="click: addSome">Add some</div>
MODEL:
function AdListModel() {
var self = this;
self.Ads = ko.mapping.fromJS([]);
self.result = function (model) {
ko.mapping.fromJS(model, self.Ads);
}
self.InitialData = function () {
$.ajax({
type: "GET",
url: '/Home/GetAllAds',
data: { startPosition: 0, numberOfItems: 2 },
dataType: "json",
success: function (data) {
self.result(data); <---- works
}
});
}
self.addSome = function () {
$.ajax({
type: "GET",
url: '/Home/GetAllAds',
data: { startPosition: 0, numberOfItems: 2 },
dataType: "json",
success: function (data) {
self.Ads.push(data); <---- doesn't work
},
});
};
self.InitialData();
}
ko.applyBindings(new AdListModel());
I tried self.Ads.push(ko.mapping.fromJS(data))
- didn't work.
Upvotes: 2
Views: 285
Reputation: 2801
It seems from the error message, that your model
does not have an AdId
property.
Can you add a dump of the JSON model returned by your API?
Edit
Your Ads
property should be an ko.observableArray()
instead of ko.mapping.fromJS([])
:
function AdListModel() {
var self = this;
self.Ads = ko.observableArray([]);
self.result = function (model) {
ko.mapping.fromJS(model, self.Ads);
}
Edit 2
And you have to map the data before pushing it:
$.ajax({
type: "GET",
url: '/Home/GetAllAds',
data: { startPosition: 0, numberOfItems: 2 },
dataType: "json",
success: function (data) {
self.Ads.push(ko.mapping.fromJS(data));
},
});
Edit 3
If your JSON looks like this:
[
{"AdId":1,"AdContent":"test1"},
{"AdId":2,"AdContent":"test2"}
]
Then it is an Array and you have to iterate over each entries:
$.ajax({
type: "GET",
url: '/Home/GetAllAds',
data: { startPosition: 0, numberOfItems: 2 },
dataType: "json",
success: function (data) {
data.forEach(function(d) {
self.Ads.push(ko.mapping.fromJS(d));
});
},
});
Upvotes: 1