Reputation: 15457
I am having a problem trying to bind my webapi data with knockoutjs. The json data comes back fine I believe but I don't know how to get it into the view model so knockout can use it?
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="Scripts/knockout-3.4.0.js"></script>
<script src="Scripts/jquery-2.1.1.js"></script>
<meta charset="utf-8" />
</head>
<body>
<table>
<thead>
<tr>
<th>Code</th>
<th>Name</th>
</tr>
</thead>
<tbody data-bind="foreach: seats">
<tr>
<td data-bind="text: Code"></td>
<td data-bind="text: Name"></td>
</tr>
</tbody>
</table>
<script type="text/javascript">
function AppViewModel() {
var self = this;
self.seats = [];
/*
[
{ Code: 1, Name: "red" },
{ Code: 2, Name: "blue" }
];
*/
$.get("/api/Test/Get", null, function (data) {
//callback
self.seats = data;
},'json');
}
ko.applyBindings(new AppViewModel());
</script>
</body>
</html>
Server-side
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace WebApplication2.Controllers
{
public class TestController : ApiController
{
[HttpGet]
public List<UserSettings> Get()
{
List<UserSettings> list = new List<UserSettings>();
UserSettings userSetting = new UserSettings() { Code = 1, Name = "Name 01" };
list.Add(userSetting);
return list;
}
}
public class UserSettings
{
public int Code { get; set; }
public string Name { get; set; }
}
}
Upvotes: 0
Views: 186
Reputation: 43881
You want seats
to be an observableArray. Then, neatly, populating it just means making it the success function for your get
:
$.get("/api/Test/Get", null, self.seats, 'json');
The example below fakes the get
with a timeout so you can see the populating happen.
function AppViewModel() {
var self = this;
self.seats = ko.observableArray();
/*
$.get("/api/Test/Get", null, self.seats, 'json');
*/
setTimeout(function() {
self.seats(
[{
Code: 1,
Name: "red"
}, {
Code: 2,
Name: "blue"
}]);
}, 800);
}
ko.applyBindings(new AppViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<table>
<thead>
<tr>
<th>Code</th>
<th>Name</th>
</tr>
</thead>
<tbody data-bind="foreach: seats">
<tr>
<td data-bind="text: Code"></td>
<td data-bind="text: Name"></td>
</tr>
</tbody>
</table>
Upvotes: 1