Reputation: 597
I'm new to knockout and I have a bit of a problem with it. I have ASP.Net MVC 4 application, razor view and knockout ViewModel. I use web api controller to get data and I cannot initialize ko.observableArray with it.
Controller function to get data:
public IEnumerable<TaskModel> GetTasks()
{
var tasks = new[] { new TaskModel { Name = "asd", Deadline = DateTime.Now, Id = new Guid() }, new TaskModel { Name = "asdfasdf", Deadline = DateTime.Now, Id = new Guid() } };
return tasks;
}
Knockout view model(call to controller is correct, data variable is not null)
function TasksList() {
var self = this;
self.tasks = ko.observableArray([]);
self.load = function() {
$.ajax({
type: "GET",
url: "http://localhost:11701/api/TaskApi",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
self.tasks(data);
},
error: function(error) {
alert(error.status + "<--and--> " + error.statusText);
}
});
};
}
var tasksList = new TasksList();
tasksList.load();
ko.applyBindings(tasksList);
View
@{
ViewBag.Title = "Index";
}
@Scripts.Render("~/Scripts/jquery-1.8.3.js")
@Scripts.Render("~/Scripts/knockout-2.2.1.debug.js")
@Scripts.Render("~/Scripts/knockout.mapping-latest.debug.js")
@Scripts.Render("~/Scripts/Models/TasksList.js")
<h2>Tasks</h2>
<table>
<tr>
<th>Name
</th>
<th>Priority
</th>
<th>Deadline
</th>
<th>CreatedOn
</th>
<th></th>
</tr>
<tbody data-bind="foreach: tasks" >
<tr>
<td data-bind="text: Name"></td>
<td data-bind="text: Priority"></td>
<td data-bind="text: Deadline"></td>
<td data-bind="text: CreatedOn"></td>
</tr>
</tbody>
</table>
I tried ko.mapping.fromJS and ko.mapping.fromJSON and it still don;t work, any idea what I'm doing wrong? Thanks in advance
Upvotes: 1
Views: 1597
Reputation: 4073
In my opinion your problem is that you have ko.applyBindings
before your HTML. Invoke that code after page load:
$(function() {
var tasksList = new TasksList();
tasksList.load();
ko.applyBindings(tasksList);
});
or at least move your javascript code to end of the body
Upvotes: 3