【问题标题】:How to bind json string in observableArray?如何在 observableArray 中绑定 json 字符串?
【发布时间】:2014-02-02 12:52:48
【问题描述】:

在我的控制器中:

 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>

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

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

【问题讨论】:

  • “选择选项中没有数据”是什么意思?如果您打开下拉列表,里面没有项目?或者您当前的位置没有预先选择?
  • 下拉列表中没有项目。你的权利就是我的意思
  • 我看不出你的代码有什么问题。我假设 self.LocationList 是一个 observableArray。不是一个普通的可观察的。你能不能稍微摆弄一下模拟数据?会更容易调试。
  • 是的,它是一个 observablearray。好的,我将为它创建一个小提琴

标签: javascript jquery html json knockout.js


【解决方案1】:

我会这样做:

// 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 与模拟 json 调用:

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

【讨论】:

    猜你喜欢
    • 2017-11-20
    • 2014-11-06
    • 2021-10-24
    • 2019-06-21
    • 2013-06-30
    • 2013-09-11
    • 1970-01-01
    • 2013-03-22
    • 2012-03-19
    相关资源
    最近更新 更多