Knockoutjs一对多映射不起作用

时间:2014-12-10 07:27:56

标签: asp.net-mvc knockout.js

在下面的代码片段中,我使用knockoutjs映射插件创建父子视图模型。我没有在映射中出现任何错误但是当我运行应用程序时它抛出错误名称未定义



data = {
                    "Id": 1,
                    "Name": "Microsoft",
                    "Address": "USA",
                    "WebPage": "SS",
                    "Employees": [
                        {
                            "Id": 1,
                            "FirstName": "sadsasa",
                            "LastName": "ADF",
                            "Twitter": "dfd",
                            "WebPage": "sdfdf"
                        },
                        {
                            "Id": 2,
                            "FirstName": "sadsasa",
                            "LastName": "ADF",
                            "Twitter": "dfd",
                            "WebPage": "sdfs"
                        },
                        {
                            "Id": 3,
                            "FirstName": "sadsasa",
                            "LastName": "ADF",
                            "Twitter": "dfd",
                            "WebPage": "sfdfs"
                        }
                        ]
                    };
        var mapping = {
            'Employees': {
                create: function (options) {
                    alert(options);
                    return new PersonViewModel(options.data);
                }
            }
        }
        function PersonViewModel(data) {
            ko.mapping.fromJS(data);
        }
        function CompanyViewModel(data) {
    
            ko.mapping.fromJS(data, mapping, this);
        }
        var company;
        $(document).ready(function () {
            $.ajax({
                url: '/api/Greet',
                type: 'GET',
                dataType: 'json',
                success: function (result) {
    
                    data = JSON.stringify(result);
                    company = new CompanyViewModel(data);
                    console.log(company);
                    ko.applyBindings(company);
                },
                error: function (e) {
                    alert(e);
                }
            });
        });
    
    
    

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div>
        FirstName:  <span data-bind="text:Name"></span>
    
    </div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

您需要在代码中进行一些小修改。

查看型号:

 function PersonViewModel(data) {
        ko.mapping.fromJS(data,mapping,this);
    }

    function CompanyViewModel(data) {
        self.childlist=ko.observableArray();
        ko.mapping.fromJS(data, mapping, this);
        self.childlist.push(new PersonViewModel()); //child array
    }

查看:

<div>
    <b>FirstName:</b>  <span data-bind="text:Name"></span>
    <div data-bind="foreach:Employees">
    <span data-bind="text:Id"></span>
    </div>
</div>

工作小提琴here

如果有任何问题,请告诉我。