javascript - 如何在 observableArray 中绑定(bind) json 字符串?

标签 javascript jquery html json knockout.js

在我的 Controller 中:

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

在我的 ko:

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

选择 html:

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

当我查看控制台日志时,结果如下: console result

结果是select选项中没有数据。任何建议如何以正确的方式做到这一点?谢谢

最佳答案

我会这样做:

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

带有模拟 json 调用的 jsFiddle:

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

关于javascript - 如何在 observableArray 中绑定(bind) json 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21113953/

相关文章:

javascript - 滑动器 slider 仅在调整窗口大小时有效

javascript - 分配变量值: Reference it instead of copying it

javascript - 忽略@RenderBody()

javascript - 需要拉取 JSON 项目的帮助

javascript - jQuery - 将 json 内容绑定(bind)到元素的简单方法?

javascript - addEventListener 不起作用,总是返回 null

javascript - jQuery 一键单击,但在某些情况下多次执行

jquery - 在以下情况下如何使用 jquery 获取文档元素的索引?

jquery - 如何通过滚动(上/下)获得显示/隐藏效果

javascript - HTML标签嵌套问题