I want to create an Observable Array from a Dynamic Model that is basically an AJAX post to obtain JSON info. I then want to add that Array to a table.
Here is my Javascript to create the Viewmodel, and what is suppose to add to array:
var ProductViewmodel;
function bindProductModel(Products) {
var self = this;
self.items = ko.mapping.fromJS([]);
ProductViewmodel = ko.mapping.fromJS(Products, self.items);
console.log(ProductViewmodel);
ko.applyBindings(ProductViewmodel);
}
function JSONProducts() {
$.ajax({
url: "WebForm1.aspx/AvailibleProducts",
// Current Page, Method
data: '{Warehouse: 1}',
// parameter map as JSON
type: "POST",
// data has to be POSTed
contentType: "application/json; charset=utf-8",
// posting JSON content
dataType: "JSON",
// type of data is JSON (must be upper case!)
timeout: 10000,
// AJAX timeout
success: function (result) {
bindProductModel(result);
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
}
The obtaining of the JSON works Perfectly:
{
"d": [
{
"__type": "Warehouse.Tracntrace.Members_Only.StockMovement.ProductStagingMethod",
"ProductSKUID": 2,
"ProductSKUName": "Decoder 1131",
"WarehouseID": 1,
"WarehouseName": "SoftwareDevelopmentTest",
"SystemAreaName": "Staging",
"Qty": 5
}
]
}
and here is where I try to Data-Bind it to my Table:
<div id="TableContainer" class="gridview">
<table border="1" cellpadding="0" cellspacing="0">
<tbody data-bind="foreach: ProductViewmodel">
<tr>
<td data-bind="text: ProductSKUID"></td>
<td data-bind="text: ProductSKUName"></td>
<td data-bind="text: WarehouseID"></td>
<td data-bind="text: WarehouseName"></td>
<td data-bind="text: SystemAreaName"></td>
<td data-bind="text: QTY"></td>
</tr>
</tbody>
</table>
</div>
It seems that it does not want to add it to my array.
Any advice would be greatly appreciated.
Regards
Jacques
You have 3 problems with your code:
data-bind="foreach: ProductViewmodel"you try to foreach on the wholeProductViewmodelbut you need to do it on theitems. So change it to<tbody data-bind="foreach: items">dproperty so you need to take care of it in your mapping. So you need to write:ProductViewmodel = ko.mapping.fromJS(Products.d, self.items);Qtyproperty name. The correct binding is:<td data-bind="text: Qty"></td>(data bindings expression are case sensitive)I’ve created a fiddle with your code which contains the fixes.