击倒绑定到drodown& json数据

时间:2018-02-27 16:47:39

标签: knockout.js

使用淘汰赛(淘汰新手),mvc c#。 我有一个下拉列表,想要从淘汰赛中填充下拉列表。 淘汰赛应该通过ajax打电话给我的mvc。我有以下代码。

<select data-bind="options: country ,optionsText: 'Text', optionsValue: 'Value'"></select>

我的淘汰赛:

(function () {
var viewModel = function () {        
    var self = this;        
    self.country = ko.observableArray();

    $.ajax({
        url: rootDir + "/Home/GetCountry",
        type: "post",
        contentType: "application/json",
        async: false,
        success: function (data) {           
            self.country = ko.observableArray(data);
        }
    });
};

var pageVM = new viewModel();
ko.applyBindings(pageVM, $("form")[0]);
})();

MVC控制器:

     public IActionResult GetCountry()
    {
        List<Country> country = new List<Country>();
        country.Add(new Country { Value = "us", Text = "United States" });
        country.Add(new Country { Value = "uk", Text = "United Kingdom" });

        var json = JsonConvert.SerializeObject(country);

        return Json(json);
    }


   public class Country
{
    public string Value { get; set; }
    public string Text { get; set; }
}

返回的json是:

[{"Value":"us","Text":"United Statesr"},{"Value":"uk","Text":"United Kingdom"}]"

我在Chrome控制台中收到错误:

Uncaught Error: The argument passed when initializing an observable array must be an array, or null, or undefined.  

1 个答案:

答案 0 :(得分:0)

你有两个问题。第一个是你试图将数组的字符串表示加载到observableArray中。那是你看到的错误。在将数据添加到数组之前,您需要在数据上调用JSON.parse。第二个问题是,当数据返回时,您将使用新的observableArray替换country observableArray。这会破坏你的约束力。将数据加载到现有数组中,而不是self.country(data)

var viewModel = function () {        
    var self = this;        
    self.country = ko.observableArray();

    var data = '[{"Value":"us","Text":"United Statesr"},{"Value":"uk","Text":"United Kingdom"}]';
    setTimeout(function () {           
        self.country(JSON.parse(data));
    }, 1000);
};

var pageVM = new viewModel();
ko.applyBindings(pageVM);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<select data-bind="options: country ,optionsText: 'Text', optionsValue: 'Value'"></select>