Reputation: 946
I have a problem on populating data using Knockout.js. Data (A HomeViewModel having 9 MainMenuModel) is successfully retrieved from Web API. I expect 9 li tag under ul tag. But HTML output is empty. Tried hard but can't solve. I appreciate any help, thanks.
Data Model Acquired from Web API
public class HomeViewModel
{
public List<MainMenuModel> MainMenus { get; set; }
}
public class MainMenuModel
{
public string Name { get; set; }
public string Url { get; set; }
}
Knockout script
function MenusViewModel() {
var self = this;
self.menus = ko.observableArray([]);
var baseUri = '/api/Home';
$.getJSON(baseUri, function (data) {
self.menus = data.MainMenus;
});
}
$(document).ready(function () {
ko.applyBindings(new MenusViewModel(), document.getElementById('mainMenus'));
});
_MainMenu.cshtml (Partial View)
<ul id="mainMenus" data-bind="foreach: menus">
<li>
<a data-bind="attr: { href: $data.Url, title: $data.Name }, text: $data.Name"></a>
</li>
</ul>
HTML Output
<ul id="mainMenus" data-bind="foreach: menus"></ul>
Upvotes: 3
Views: 308
Reputation: 139798
ko.observable
and ko.observableArray
are functions. To assign them a new value you need to call them with the new value as the argument.
See also the documentation: Reading and writing observables.
So change your code in $.getJSON
to:
$.getJSON(baseUri, function (data) {
self.menus(data.MainMenus);
});
Upvotes: 2