简体   繁体   中英

How to bind json string in observableArray?

In my controller:

 public ActionResult GetCountryList() {
     return Json(new {data = db.Country.ToList()},JsonRequestBehavior.AllowGet);
 }

in my ko:

self.GetCountryList = function () {
    $.getJSON("/ProfileCore/GetCountryList", function (result) {
        self.LocationList(result.data);
        console.log(self.LocationList());
    })
};

select html:

<select data-placeholder="Location" class="chosen-select" style="width:100%;" tabindex="2" data-bind="options:LocationList, optionsText:'CountryName', optionsValue:'Id', value:Location"></select>

when I view the console log this is the result: 控制台结果

the result is there is no data in select option. any suggest in how to do this in the right way? thanks

This is how I would do it:

// Create an object 
var Country = function (Id, Name) {
        self = this;
        self.Id = Id;
        self.CountryName = Name;
    }

// Create a mapping object
    var mapping = {
        'LocationList': {
            create: function(options) {
                return new Country(options.data.Id, options.data.CountryName);
            }
        }
    }

// Create the view model
function AViewModel()
{
  var self = this;  
    self.LocationList = ko.observableArray();
    self.Location = ko.observable("2");

    // Map the json to the view model
    $.ajax({
       url:"/echo/json/",
       data:data,
       type:"POST",
       success:function(response)
       {
         self.LocationList = ko.mapping.fromJS(response, mapping, self);
       }
    });


}

var viewModel = new AViewModel();
ko.applyBindings(viewModel);

jsFiddle with mock json call:

http://jsfiddle.net/hutchonoid/Tnyqp/10/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM