无法分配Json字符串数组

时间:2014-02-01 09:32:11

标签: jquery asp.net-mvc knockout.js

GetAllCountries从控制器操作(MVC)检索国家/地区列表。我无法将国家/地区分配给选择元素(如标记中所示)。另一方面,如果我将值指定为model.countries = ["India","USA"];则可行。如何分配返回值?

var initialData = @Html.Raw(new JavaScriptSerializer().Serialize(Model));


    function StudentViewModel() {
        var self = this;
        self.students = ko.observableArray([]);
        self.countries =[];
        self.editingItem = ko.observable();
        self.isItemEditing = function(itemToTest) {
            return itemToTest == self.editingItem();
        };
    };
    $(document).ready(function () {
        var url = '/GridDemo/GetAllCountries';
        $.ajax({ url: url, success: dataRetrieved, type: 'POST', dataType: 'json' });
        var model = new StudentViewModel();
        //model.countries = ["India","USA"];
        function dataRetrieved(data) {
            var strCountry = [];
            for (var i = 0; i<data.length; i++) {
                strCountry.push(data[i]);
            }
            //alert(strCountry);
           model.countries = strCountry;

        }
       // alert(initialData.country);
        //model.countries = initialData.Countries;
        model.students(initialData);
        ko.applyBindings(model);   

    });

HTML:

 <select class="form-control" data-bind="options: $root.countries, value: 
  Country, visible: $root.isItemEditing($data)"></select>
 <label data-bind="text: Country, visible: !$root.isItemEditing($data)" />

当我弹出json结果时,我得到的确是:印度,美国,尼泊尔。

控制器中的动作:

 public JsonResult GetAllCountries()
        {
            var countries = new[] { "India", "America", "Nepal" };
            return Json(countries, JsonRequestBehavior.AllowGet);
        }

1 个答案:

答案 0 :(得分:1)

您需要将countries设为ko.observableArray

function StudentViewModel() {
        var self = this;
        self.students = ko.observableArray();
        self.countries = ko.observableArray();
        self.editingItem = ko.observable();
        self.isItemEditing = function(itemToTest) {
            return itemToTest == self.editingItem();
        };
    };

在您的dataRetrieved中,您需要将strCountry分配给model.countries

function dataRetrieved(data) {
    var strCountry = [];
    for (var i = 0; i<data.length; i++) {
        strCountry.push(data[i]);
    }
    model.countries(strCountry);
}

或者您可以直接push进入您的可观察数组(documentation):

function dataRetrieved(data) {
    model.countries.removeAll();
    for (var i = 0; i<data.length; i++) {
        model.countries.push(data[i]);
    }
}