我的应用程序是MVC 5,我使用以下Knockout-kendo下拉列表:
<input data-bind="kendoDropDownList: { dataTextField: 'name', dataValueField: 'id', data: foodgroups, value: foodgroup }" />
var ViewModel = function () {
var self = this;
this.foodgroups = ko.observableArray([
{ id: "1", name: "apple" },
{ id: "2", name: "orange" },
{ id: "3", name: "banana" }
]);
var foodgroup =
{
name: self.name,
id: self.id
};
this.foodgroup = ko.observable();
ko.bindingHandlers.kendoDropDownList.options.optionLabel = " - Select -";
this.foodgroup.subscribe(function (newValue) {
newValue = ko.utils.arrayFirst(self.foodgroups(), function (choice) {
return choice.id === newValue;
});
$("#object").html(JSON.stringify(newValue));
alert(newValue.name);
});
};
ko.applyBindings(new ViewModel());它工作得很好,多亏了这个答案Knockout Kendo dropdownlist get text of selected item
但是,当我将observableArray更改为Ajax时:
this.foodgroups = ko.observableArray([]),
$.ajax({
type: "GET",
url: '/Meals/GetFoodGroups',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
self.foodgroups(data);
},
error: function (err) {
alert(err.status + " : " + err.statusText);
}
});控制器-从ms sql server获取表:
public JsonResult GetFoodGroups()
{
var data = db.FoodGroups.Select(c => new
{
id = c.FoodGroupID,
name = c.FoodGroupName
}).ToList();
return Json(data, JsonRequestBehavior.AllowGet);
}

当我警告项目名称时,我会得到这个错误。
Unable to get property 'name' of undefined or null reference用Ajax对数组项进行硬编码有什么区别。
发布于 2016-02-17 14:07:29
“id”字段在硬编码数组中具有字符串数据类型。

'id‘字段在ajax数组中具有编号数据类型。

。
因此,“id”字段在两个数组中都有不同的数据类型。但是,在情况下,您使用了===运算符,因此它检查值以及数据类型。

对于ajax,数组值相同,但其数据类型不同,因此不返回结果。
如果有任何担心的话请告诉我。
https://stackoverflow.com/questions/35400673
复制相似问题