2

I want to update KnockoutJS viewmodel from AJAX JSON entry. I am unsure how to do this.

Here is my code:

 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);
    })

And here is the JSON Data that is obtained from the server:

{
"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>

The Viewmodel Is extremely Simple, I have a currency From, and A currency to that I want to add and remove from a table.

2 Answers 2

2

I'd do two things here.

First, define a class for Currency.

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

After that, your success method becomes something like this.

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);
}
Sign up to request clarification or add additional context in comments.

Comments

0

I suggest you to separate viewmodel and datacontext. It's a better practice to have a class for your ajax request

I supose that you need to bind you array "self.Currencies" with data received from a service, so you only need to do this on your success function:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.