使用knockoutjs绑定和显示字典

bind and Display dictionary with knockoutjs

本文关键字:显示 字典 绑定 knockoutjs 使用      更新时间:2023-11-21

我使用敲除,我的视图模型中有一个Observalearray(mappedCompaignByInterest),它包含对象数组,每个对象就像字典,它包含字符串键和对象数组值(Compaign)。请告诉我如何将这个对象与knockoutjs上的表绑定。

这是我的视图模型:

    function DashboardViewModel() {
    var self = this;        
    self.BuzzCompaignByInterest = ko.observableArray([]);

}

这是用于从服务器加载数据

  //    Load initial state from server,
    $.getJSON("/Dashboard", function (Data) {            
        var mappedCompaignByInterest = Data.BuzzCompaignByInterest;            
        self.BuzzCompaignByInterest(mappedCompaignByInterest);                        
       });

注意,Data.BuzzCompaignByInterest希望我从服务器获得它是一个字典,键是一个字符串,值是一个对象数组(Compaign)这是Compaign:类的属性

 public class BuzzCompaignModel
{
    public long BuzzCompaignId { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
 }

请告诉我如何显示BuzzCompapignByInterest(视图模型中的可观测阵列)的数据

我假设您的字典项看起来像这样的类:

function DictionaryItem(key, value) {
                this.key = key;
                this.value = value;
            }

BuzzCompaignModel的值在哪里?它看起来像这样:

function BuzzCompaignModel(id, name, description) {
            this.id = id;
            this.name = name;
            this.description = description;
        }

在使用初始化的BuzzCompaignModel分配DictionaryItem集合后,您可以通过以下方式绑定此数组:

    <table>
        <tbody data-bind="foreach:BuzzCompaignByInterest">
            <tr>
                <td data-bind='text:key'></td>
                <td data-bind='text:value.id'></td>
                <td data-bind='text:value.name'></td>
                <td data-bind='text:value.description'></td>
            </tr>
        </tbody>
    </table>

还有jsfiddle示例