loading a knockout.js observableArray() from .ajax() call
There is no reason this would not work fine. As this demonstrates.
http://jsfiddle.net/madcapnmckay/EYueU/
I would check that the ajax post is actually returning json data and that that json is an array and that it's being parsed correctly.
I had to tweak the ajax call to get the fiddle ajax handlers to work correctly.
Nothing more I can think of.
Hope this helps.
var self=this;//var self first line in model$.ajax({ url: ", dataType: "json", contentType: 'application/json', type: "POST", data: JSON.stringify({ }), processdata: true, beforeSend: function () { $.mobile.loading('show'); }, error: function (xhr, textStatus, errorThrown) { alert('Sorry!'); }, success: function (data) { $.mobile.loading('hide'); if (data.result!= '') { self.vendors(data.result); } else { self.vendors({something}); } } });
Use self.vendors not this viewModel.vendors
Here is what I done in my MVC .net app with knockout and jquery.
// Scripts/groItems.js(function () { var ViewModel = function () { items = ko.observableArray(), ItemName = ko.observable(), Img = ko.observable(), Qty = ko.observable() } $.getJSON('/Items2/AllItems', function (data) { for (var i = 0; i < data.length; i++) { self.items.push(data[i]); } }); var vm = new ViewModel(); $(function () { ko.applyBindings(vm); });}());
@model IEnumerable<GroModel.Item>@{ ViewBag.Title = "Index";}<p> @Html.ActionLink("Create New", "Create")</p><div data-bind="text: items().length"></div><table class="container table table-hover"> <thead> <tr> <th>Item name</th> <th>img</th> <th>qty</th> </tr> </thead> <tbody data-bind="foreach: items"> <tr> <td data-bind="text: ItemName"></td> <td data-bind="text: Img"></td> <td data-bind="text: Qty"></td> </tr> </tbody></table>@section Scripts { <script src="~/Scripts/knockout-3.4.2.js"></script> <script src="~/Scripts/groItems.js"></script>}
Following is part of my code at the Items2Controller.cs
private GroContext db = new GroContext(); public JsonResult AllItems() { return Json(db.Items.ToList(), JsonRequestBehavior.AllowGet); }
Hope this will help. Thanks