Knockout-Kendo dropdownlist Ajax observableArray 获取选中项名称
Posted
技术标签:
【中文标题】Knockout-Kendo dropdownlist Ajax observableArray 获取选中项名称【英文标题】:Knockout-Kendo dropdownlist Ajax observableArray get selected item name 【发布时间】:2016-05-25 20:24:00 【问题描述】:我的应用程序是 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 有什么区别。
【问题讨论】:
你在哪里得到 tis 错误?在阿贾克斯Success()
?
当我尝试获取所选项目的名称时。阿贾克斯作品
你可以在分配success()
数据后记录self.foodgroups()
吗?
不知道你说的log是什么意思,我得到的是下拉列表的内容,当我选择一个项目时,我在subscribe(function (newValue)之后得到了正确的id。
我的意思是显示您从控制器收到的数据,但您对 Ajax 和硬编码有相同的看法,对吧?
【参考方案1】:
“id”字段在硬编码数组中具有 string 数据类型。
'id' 字段在 ajax 数组中具有 number 数据类型。
.
因此,“id”字段在两个数组中具有不同的数据类型。但是,在您使用 === 运算符的条件下,它会检查 value 以及 datatype。
对于 ajax 数组值相同,但数据类型不同,因此不返回结果。
如果有任何问题,请告诉我。
【讨论】:
很好,我使用了 return choice.Groupid === parseInt(newValue);效果很好,谢谢。 我的意思是 id === parseInt(newValue);以上是关于Knockout-Kendo dropdownlist Ajax observableArray 获取选中项名称的主要内容,如果未能解决你的问题,请参考以下文章