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