无法使用数据初始化可观察数组

时间:2013-03-12 20:19:07

标签: asp.net-mvc-4 knockout.js

我是淘汰赛的新手,我有点问题。我有ASP.Net MVC 4应用程序,razor视图和淘汰ViewModel。我使用web api控制器来获取数据,我无法用它初始化ko.observableArray。

获取数据的控制器功能:

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

淘汰视图模型(调用控制器是正确的,数据变量不为空)

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);

查看

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

我尝试过ko.mapping.fromJS和ko.mapping.fromJSON但它仍然没有工作,任何想法我做错了什么?提前致谢

1 个答案:

答案 0 :(得分:3)

在我看来,您的问题是您的HTML之前有ko.applyBindings。在页面加载后调用该代码:

$(function() {
    var tasksList = new TasksList();
    tasksList.load();
    ko.applyBindings(tasksList);
});

或者至少将您的javascript代码移到正文末尾