1

我需要一些帮助来弄清楚如何将 JSON 结果绑定到 MVC4 中的视图。

我有以下视图模型,它返回看似正确的 JSON;

视图模型是

function task(name, duedate, overdue, phase, project, description, groups) {

var self = this;

self.name = ko.observable(name);
self.duedate = ko.observable(duedate);
self.overdue = ko.observable(overdue);
self.phase = ko.observable(phase);
self.project = ko.observable(project);
self.description = ko.observable(description);
self.group = ko.observable(groups);
}


function bTask() {
var self = this;
var parts = document.location.href.split("/");
var id = parts[parts.length - 1];
self.atasks = ko.observableArray([]);

$.getJSON("/api/tasks/GetProjectTasks?id="+id+"&stat=Active", function (data) {
    $.each(data, function (key, val) {
        self.atasks.push(new task(val.Name, moment(val.DueDate).format('DD/MM/YYYY'),  val.overdue, val.Phase, val.Project, val.Description, val.Goups));

    });
 });
}

$(document).ready(function () {
var aTask = new bTask();


ko.applyBindings(aTask, document.getElementById('activetasks'));

function onLoop() {
    var self = aTask;
    var parts = document.location.href.split("/");
    var id = parts[parts.length - 1];

    $.getJSON("/api/tasks/GetProjectTasks?id=" + id + "&stat=Active", function (data) {
        self.atasks.removeAll();
        $.each(data, function (key, val) {
           self.atasks.push(new task(val.Name,  moment(val.DueDate).format('DD/MM/YYYY'), val.overdue, val.Phase, val.Project,  val.Description, val.Goups));
         });

     });



  }

 setInterval(onLoop, 10000);
});

api返回的JSON如下;

[{"$id":"1","DueDate":"2013-06-05T00:00:00","Id":4,"Name":"Address UAT    Issues","Description":"Task 4 Description","Status":"Active","Phase":"Requirements   Review","Project":"RAP C1","StartDate":"2013-05-31T17:28:55.46","overdue":"error","Groups":  [{"$id":"2","Name":"Group 1","Description":"Group 1   Description","ClientId":1,"GroupType":null,"Id":1},{"$id":"3","Name":"Group   2","Description":"Group 2 Description","ClientId":1,"GroupType":null,"Id":2}]}]

如您所见,它返回 1 个包含两个组的任务,这是正确的。

在我的视图中循环访问任务允许我访问任务的任何属性,但我不确定如何访问返回的组和属性。

我如何需要在视图中绑定到这个?

我可以在 foreach 的任务中 foreach 吗?

任何帮助解释这一点都非常感谢。

提前致谢

约翰

4

1 回答 1

0

You can use the foreach binding.

I made a fiddle based on your data.

<div data-bind="foreach : Groups">
    <span data-bind="text : $id"></span>
    <span data-bind="text : Name"></span>
    <span data-bind="text : Description"></span>
    <span data-bind="text : GroupType"></span>    
    <span data-bind="text : Id"></span>
    <br/>
</div>

I hope it helps.

于 2013-06-15T20:42:22.197 回答