0

这是我第一次工作并尝试淘汰 js,但我无法让它工作。我正在做的是显示从数据库返回的列表/集合 - 基本上是所有用户及其信息的获取。

问题: 到目前为止,我没有让数据显示在页面上,也不确定我做错了什么或遗漏了什么。如果我缺少任何其他有助于解决我的问题的代码,请告诉我。谢谢!

查看页面

@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>

模型

 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
    }
4

2 回答 2

0

查看您的代码,我想您正在使用 ASP.NET WebAPI。我认为您应该将您的 ajax 调用地址从 更改/api/RosterApiController/api/RosterApi.

Both ASP.NET MVC and ASP.NET WebAPI have routing convention that except controller name without Controller suffix.

于 2013-03-29T20:47:35.763 回答
0

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));
});
于 2013-03-29T22:24:54.063 回答