Reputation: 645
The GetAllCountries retrieve list of countries from controller action(MVC).I am unable to assign the countries to select element( as shown in the mark up). On the other hand if I assign values as model.countries = ["India","USA"];
it worked. How do I assign the return values?
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)" />
When I pop up the json result I got exactly: India,America,Nepal.
Action in the controller:
public JsonResult GetAllCountries()
{
var countries = new[] { "India", "America", "Nepal" };
return Json(countries, JsonRequestBehavior.AllowGet);
}
Upvotes: 0
Views: 95
Reputation: 139758
You need to make your countries
also an 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();
};
};
And in your dataRetrieved
you need to assign the strCountry
to the model.countries
:
function dataRetrieved(data) {
var strCountry = [];
for (var i = 0; i<data.length; i++) {
strCountry.push(data[i]);
}
model.countries(strCountry);
}
Or you can directly push
into your observable array (documentation):
function dataRetrieved(data) {
model.countries.removeAll();
for (var i = 0; i<data.length; i++) {
model.countries.push(data[i]);
}
}
Upvotes: 1