将Ajax JSON POST方法绑定到KnockoutJS Viewmodel

时间:2013-01-16 12:49:56

标签: json knockout.js

我想从AJAX JSON条目更新KnockoutJS viewmodel。我不确定该怎么做。

这是我的代码:

 var CurrencyModel = function (Currencies) {
        var self = this;
        self.Currencies = ko.observableArray(Currencies);

        self.AddCurrency = function () {
            self.Currencies.push({
                CurrencyFrom: "",
                CurrencyTo: ""
            });
        };

        self.RemoveCurrency = function (Currency) {
            self.Currencies.remove(Currency);
        };

        self.Save = function (Form) {
            alert("Could Now Save: " + ko.utils.stringifyJson(self.Currencies));
        };

        $.ajax({
            url: "CurrencyConfiguration.aspx/GetConfiguredCurrencies",
            // Current Page, Method  
            data: '{}',
            // parameter map as JSON  
            type: "POST",
            // data has to be POSTed  
            contentType: "application/json; charset=utf-8",
            // posting JSON content      
            dataType: "JSON",
            // type of data is JSON (must be upper case!)  
            timeout: 10000,
            // AJAX timeout  
            success: function (Result) {
                //Need to Get method to Bind To CurrencyModel;
            },
            error: function (xhr, status) {
                alert(status + " - " + xhr.responseText);
            }
        });
    };

    $(document).ready(function () {
        var VM = new CurrencyModel();
        ko.applyBindings(VM);
    })

这是从服务器获取的JSON数据:

{
"d": [
    {
        "__type": "Finance.Tracntrace.Members_Only.DAL.DataModel.Currency.CurrencyConfigurationDM",
        "CurrencyFrom": "ZAR",
        "CurrencyTo": "USD"
    },
    {
        "__type": "Finance.Tracntrace.Members_Only.DAL.DataModel.Currency.CurrencyConfigurationDM",
        "CurrencyFrom": "USD",
        "CurrencyTo": "ZAR"
    }
]
}

HTML:

  <table class="table table-striped">
            <thead>
                <tr>
                    <th>
                        Currency From
                    </th>
                    <th>
                        Currency To
                    </th>
                </tr>
            </thead>
            <tbody data-bind="foreach: Currencies">
                <tr>
                    <td data-bind="text: CurrencyFrom">
                    </td>
                     <td data-bind="text: CurrencyTo">
                    </td>
                </tr>
            </tbody>
        </table>

Viewmodel非常简单,我有货币From和A货币到我要在表格中添加和删除的货币。

2 个答案:

答案 0 :(得分:2)

我在这里做两件事。

首先,为Currency定义一个类。

var currency = function(data) {
  var self = this;
  self.CurrencyFrom = ko.observable(data.CurrencyFrom);
  self.CurrencyTo = ko.observable(data.CurrencyTo);
}

之后,你的成功方法会变成这样。

success: function(Result) {
   // use jQuery's $.map function to translate values
   // should be stored in .d property, according to your JSON
   var mappedCurrencies = 
     $.map(Result.d, 
           // Here, $.map will just new up a new currency,
           // using the constructor argument to set fields
           function(item){ return new currency(item);});

   // Finally, set the currencies.  VM should update automatically.
   self.Currencies(mappedCurrencies);
}

答案 1 :(得分:0)

我建议你分开viewmodel和datacontext。为ajax请求创建一个类是更好的做法

我认为您需要将数组“self.Currencies”与从服务接收的数据绑定,因此您只需要在成功函数上执行此操作:

       success: function (Result) {
            ko.utils.arrayPushAll(self.Currencies, Result);
        }