在我的控制器中:
public ActionResult GetCountryList() {
return Json(new {data = db.Country.ToList()},JsonRequestBehavior.AllowGet);
}
in my 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>
当我查看控制台日志时,这是结果:
结果是select选项中没有数据。如何以正确的方式做到这一点?感谢
答案 0 :(得分: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 with mock json call: