3

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>

1 Answer 1

2

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);
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.