I have this view:
<tbody data-bind="foreach: dataSource">
<tr data-bind="if: Enabled && DefaultSupplier.Enabled">
<td><input type="checkbox" data-bind="attr: { value: Id }, checked: $root.selectedIds" /></td>
<td data-bind="text: Reference"></td>
<td data-bind="text: Description"></td>
<td data-bind="text: DefaultSupplier ? DefaultSupplier.Name.Name : ''"></td>
<td data-bind="text: CurrentStock"></td>
</tr>
</tbody>
The last property, CurrentStock
, must be retrieved using an AJAX call.
//know how many articles in stock
this.CurrentStock = ko.computed(function () {
$.ajax({
url: "/StockLines/GetArticleCurrentStock?ArticleId=" + { value: Id },
method: "GET",
dataType: 'json',
success: function (data) {
return data;
}
});
});
The problem is that the Id of the article, can be retrieved from the view like this
<td data-bind="text: Id"></td>
But I can't pass it to the ajax call as a parameter like this { value: Id }
. This does not work.
I would really appreciate some help because I'm new in the whole KNOCKOUT thing and I'm very excited about it and interested in learning how to use it for future projects.
I finally did another approach that worked for me.
View
<h5>@ApplicationResources.Question_ShowOutOfStocks</h5><input type="checkbox" data-bind="checked: show" />
<!-- List of articles out of stock -->
<table>
<tbody data-bind="foreach: stocks, visible: show">
<tr style="color: red">
<td style="width: 3em">
<input type="checkbox" data-bind="attr: { value: id }, checked: $root.selectedIds" />
</td>
<td data-bind="text: reference" style="width: 10%" ></td>
<td data-bind="text: description" style="width: 35%" ></td>
<td data-bind="text: supplier" ></td>
<td data-bind="text: stock" ></td>
</tr>
</tbody>
</table>
ViewModel
// Array of articles out of stock
self.stocks = ko.observableArray([]);
// Boolean show
self.show = ko.observable(true);
// Stock ViewModel
function Stock(data) {
this.id = ko.observable(data.id);
this.reference = ko.observable(data.reference);
this.description = ko.observable(data.description);
this.supplier = ko.observable(data.supplier);
this.stock = ko.observable(data.stock);
}
// Load data from server
$.getJSON("/Requests/GetOutOfStocks", function (allData) {
var mappedTasks = $.map(allData, function (item) { return new Stock(item) });
self.stocks(mappedTasks);
});
Hope this helps to someone else because it saved my life!