如何在淘汰赛中将Json数据绑定到Html

时间:2015-05-10 03:33:09

标签: javascript html knockout.js

我从json对象收到以下数据,

var dataFromServer='[
    {
        "Id":1,
        "Name":"Province A",
         "AreaDTO":[],
         "SubStationDTO":[]
    },
    {
         "Id":2,
         "Name":"Province B",
          "AreaDTO":[
              {
                  "Id":1,
                  "Name":"ProvinceB Area A",
                  "ProvinceId":2,
                  "SubStationDTO":null
              },
              {
                  "Id":2,
                  "Name":"Province B Area B",
                  "ProvinceId":2,
                  "SubStationDTO":null
              }],
          "SubStationDTO":[
              {
                  "Id":1,
                  "Name":" Province B Area A SubStation A",
                  "AreaId":1,
                  "MetersDTO":null
              }     
          ]
    }
]';

请参阅:http://jsfiddle.net/Jayaruvan/s8403t71/1/

<table class="table table-bordered table-condensed">
    <thead>
    <tr>
        <th>Province Name</th>
        <th class="numeric">Area Count</th>
        <th class="numeric">SubStation Count</th>
        <th colspan="2"></th>
    </tr>
    </thead>
    <tbody data-bind="foreach: ProvincesArray">
    <tr>
        <td><p data-bind="text: Name"></p></td>
        <td ><p data-bind="text: Areas().length" ></p></td>
        <td> <p data-bind="text: SubStations().length" ></p></td>
        <td class=""><a class="btn-link" data-bind="click: $parent.EditProvince">Edit</a></td>
        <td class=""><a class="btn-link" data-bind="click: $parent.RemoveProvince">Delete</a></td>

    </tr>
    </tbody>
</table>

我希望它绑定在表格之上,但它不起作用。有人可以帮忙吗?

我指的是:http://jsfiddle.net/rVPBz/2/作为例子, (感谢ace的正确格式化)

1 个答案:

答案 0 :(得分:0)

我为你做了一个新的Jsfiddle。我已经解决了一些基本错误。

该表已实施。

您的视图模型实现很糟糕,我对其进行了重组。

var ProvinceViewModel = function () {
    var self = this;

    this.Province = function(data){ 
        data = data || {};

        this.Id = data.Id;
        this.Name=data.Name;
        this.Areas = ko.observableArray([]);
        this.SubStations = ko.observableArray([]);
    };

    this.ProvincesArray = ko.observableArray([new     this.Province()]);

    this.Area = function(data){
    data = data || {};

        this.Id = ko.observable(data.Id);
        this.Name = ko.observable(data.Name);
        this.SubStations = ko.observableArray([]);
    };

    this.SubStation = function(data){
       data = data || {};

        this.Id = ko.observable(data.Id);
        this.Name = ko.observable(data.Name);
        this.Meters = ko.observableArray([]);
    };    

    this.ProvincesArray = ko.utils.arrayMap(dataFromServer,            function(item) {

        var Province = new self.Province(item);
        var Area= new self.Area(item);
        var SubStations= new self.SubStation();

        return Province;
    });
};
ko.applyBindings(new ProvinceViewModel());

你可以看到有效的新结构,你可以添加任何参数

http://jsfiddle.net/YvanBarbaria/s8403t71/15/