Reputation: 1032
I have the following line:
$.getJSON('@Url.Action("RegistrationShareClassReport", new { id = ViewBag.Id })', function (data) {
viewModel.RegistrationShareClassReport(data);
});
This basically returns data in json format with different elements. e.g.
id = "2",
name = "tj",
country = "GB"
id = "3",
name = "pj",
country = "IT"
What i want to is from that viewmodel populate an array of all the countries for each item. So i would need to loop through the viewmodel data and extract the countries from each.
I wanted to know i could achieve this in knockout.js?
thanks
Upvotes: 0
Views: 401
Reputation: 31
You can use the Knockout mapping plugin (http://knockoutjs.com/documentation/plugins-mapping.html) to map your json to your viewmodel.
Here's some code to get you started. Adjust it to your own needs:
<script type="text/javascript">
$.getJSON("/data.json", function (data) {
var viewModel = {};
var mapping = {
"countries": {
key: function (data) {
return ko.utils.unwrapObservable(data.name);
}
}
};
viewModel = ko.mapping.fromJS(data, mapping);
ko.applyBindings(viewModel);
});
</script>
And then in HTML:
<ul data-bind="foreach: $root">
<li data-bind="text: name"></li>
</ul>
Upvotes: 1