gpt4 book ai didi

asp.net-mvc - Knockout-Kendo dropdownlist Ajax observableArray 获取选中项名称

转载 作者:行者123 更新时间:2023-12-02 04:25:56 25 4
gpt4 key购买 nike

我的应用程序是 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);
}
});

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

enter image description here

当我提醒项目名称时,出现此错误

 Unable to get property 'name' of undefined or null reference

对数组项进行硬编码与使用 Ajax 有何区别。

最佳答案

“id”字段在硬编码数组中具有字符串数据类型。

enter image description here

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

enter image description here .

因此,两个数组中的“id”字段具有不同的数据类型。但是,如果您使用了 === 运算符,那么它会检查以及数据类型

enter image description here

对于ajax数组值是相同的,但它的数据类型不同,所以它不返回结果。

如果有任何疑问,请告诉我。

关于asp.net-mvc - Knockout-Kendo dropdownlist Ajax observableArray 获取选中项名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35400673/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com