Firstly, this is my first post on stack overflow and its an honor to be part of this community. I need help. I am using mvc and knockout.js. I have a Model with a list object of data. I create another one and select only 5 from the original. The reason for this is to filter upon the original set of data but only show certain data from the original list.
var data = @Html.Raw(Json.Encode(Model));
self.CartModel = ko.wrap.fromJS(data);
self.CartModel.FilteredData = ko.computed(function () {
return self.CartModel.OriginalData().slice(0, 5);
}, self);
<div id="NbId" class="listing-style3" data-bind="foreach: Cart.CartModel.FilteredData">
<article class="box">
<figure class="col-sm-5 col-md-4">
<img style="width:270px; height: 160px; " alt="" data-bind="attr:{src:Image}">
</figure>
<div class="details col-sm-7 col-md-8">
<div>
<div>
<img data-bind="attr:{src:RatingUrl}" />
</div>
</div>
<div>
<p data-bind="text: Teaser"></p>
</div>
</div>
</article>
</div>
This works fine and the foreach in the html renders fine. What I need help with is when I make another call to the server and get a new data source, how do I re-render the html for-each part?
I have tried setting the CartModel to the new datasource as well as the Filtered data in the same way as mentioned above, and the new data is present, but the html does not change.
$.ajax({
cache: false,
type: "POST",
contentType: 'application/json; charset=utf-8',
url: url,
data: requestAvailability,
success: function (data) {
var response = data.NewData;
CartApp.Cart.CartModel = ko.wrap.fromJS(response);
CartApp.Cart.CartModel.FilteredData = ko.computed(function () {
return CartApp.Cart.CartModel.OriginalData().slice(0, 5);
}, CartApp.Cart);
//targetDiv.html();
//targetDiv.html(data);
}
//, error: function (xhr) {
// var status = xhr.status;
// var responseText = xhr.responseText;
// //alert("Error "+ status+" - "+ responseText);
//}
});
I am new to knockout and would appreciate any assistance. Thanks in advance
You need an observable CartModel defined outside ajax call:
in the ajax success you should put new value into this observable:
and change your binding in the markup
In this case you will have the only observable CardModel, knockout will subscribe to it and rebuild markup after it's value changed.