This is my first time working and trying out knockout js and i am having trouble getting it to work. What i am doing is displaying a list/collection being returned from the database - basically a get of all users with their information.
Problem: with what i have written so far i am not getting the data to display on the page and not sure what i am doing wrong or missing. If i am missing any other code that will help resolve my issue let me know. Thanks!
View Page
@using ProjectB.Shared.Models
@using System.Collections
@using ProjectB.Shared.Services
<html>
<head>
<script type ="text/javascript" src="~/Scripts/jquery-1.9.1.min.js"></script>
<script src="~/Scripts/knockout-2.2.1.js"></script>
<script src="~/Scripts/knockout.mapping-latest.js"></script>
</head>
<body>
<table data-bind="visible: RosterUsers().length>0">
<thead>
<tr>
<td>Name</td>
<td>Content Role</td>
<td>Email</td>
<td></td>
</tr>
</thead>
<tbody data-bind="foreach: RosterUsers">
<tr>
<td><span data-bind="text: Name"></span></td>
<td><span data-bind="text: ContentRole"></span></td>
<td><span data-bind="text: Email"></span></td>
</tr>
</tbody>
</table>
<script type ="text/javascript">
var rUserViewModel = function () {
var self = this;
self.Name = ko.observable("");
self.ContentRole = ko.observable("");
self.Email = ko.observable("");
var rUserData = {
Name: self.Name,
ContentRole: self.ContentRole,
Email: self.Email
};
self.RosterUsers = ko.observableArray([]);
GetRosterUser();
function GetRosterUser() {
$.ajax({
type: "GET",
url: "/api/RosterApiController",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
self.RosterUsers(data);
},
error: function (error) {
alert(error.status + " <--and--> " + error.statusText);
}
});
}
};
ko.applyBindings(new rUserViewModel());
</script>
</body>
</html>
Model
public partial class RosterVw
{
public RosterVw()
{
this.Users = new HashSet<RosterUser>();
}
public ICollection<RosterUser> Users { get; set; }
}
public partial class RosterUser
{
public string Name { get; set; }
public ContentRoles ContentRole { get; set; }
public string Email { get; set; } //Photo is unique to email address
}
Looking at your code I suppose that you are using ASP.NET WebAPI. I thing that you should change your ajax call address from /api/RosterApiController
to /api/RosterApi
.
Both ASP.NET MVC and ASP.NET WebAPI have routing convention that except controller name without Controller
suffix.
I think Slawomir solution is definitely something you should be aware of but you can try to populate your RosterUsers using a foreach.
_.each(data, function(user){
self.RosterUsers.push(new RosterUserObject(user));
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.