Trying to populate a table using Knockout.
Controller:
public JsonResult GetAllStudents()
{
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(_apiInfo.Urlapi);
MediaTypeWithQualityHeaderValue contentType =
new MediaTypeWithQualityHeaderValue("application/json");
client.DefaultRequestHeaders.Accept.Add(contentType);
HttpResponseMessage response = client.GetAsync("/api/students").Result;
string stringData = response.Content.ReadAsStringAsync().Result;
if (response.IsSuccessStatusCode)
{
return Json(stringData);
}
return null;
}
}
View:
<table>
<thead>
<tr><th>Last name</th></tr>
</thead>
<tbody data-bind="foreach: people">
<tr>
<td data-bind="text: $data.lastName"></td>
</tr>
</tbody>
</table>
Script:
function AppViewModel() {
var self = this;
self.people = ko.observableArray([]),
$.ajax({
type: "GET",
url: '@Url.Action("GetAllStudents", "Konckout")',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
self.people(data);
},
error: function (err) {
alert(err.status + " : " + err.statusText);
}
});
}
ko.applyBindings(new AppViewModel());
I tested the return using alert(data), got the following:
[{"id":1,"lastName":"Alexander"},{"id":1,"lastName":"Mike"}]
However no data is displayed in the table!