从对象数组中敲出foreach绑定

时间:2017-05-02 06:41:02

标签: html knockout.js

我是淘汰赛的新手。我想列出学生名单。

我附加了从MVC返回的列表结构image, Click here to view

Js代码:

var employeeListViewModel = {};
var employeeViewModel = {
    id: "",
    name: ko.observable("neenu"),
    age: ko.observable(),
    email: ko.observable(),
    department: ko.observable(),
    address: {
        address1: ko.observable(),
        city: ko.observable(),
        State: ko.observable()
    },
};
var employeePageViewModel = {
    employee: employeeViewModel,
    employees: employeeListViewModel
};
var dataSource = {
    getemployees: function () {
        getData("Employee/GetEmployees").then((data) => {
            var result = ko.mapping.fromJS(data.data);
            employeeListViewModel = result();
            console.log(employeeListViewModel);
        });
    },
    init: function () {
        this.getemployees();
    }
}.init();
ko.applyBindings(employeePageViewModel);

Html代码:

<thead>
    <tr>
        <th>First name</th>
        <th>Last name</th>
    </tr>
</thead>
<tbody data-bind="foreach: employees">
    <tr>
        <td data-bind="text: Name"></td>
        <td data-bind="text: Id"></td>
    </tr>
</tbody>

当我运行此页面时,它既不显示任何错误也不显示数据。请帮忙。

1 个答案:

答案 0 :(得分:1)

1)employeeListViewModel必须是ko.observableArray()
2)从getData函数获取结果时,只需将observableArray设置为列表:

employeeListViewModel(data.data); //assuming data.data is a [].

3)ko.mapping.fromJS(data.data);可以删除