【发布时间】: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 和硬编码有相同的看法,对吧?
标签: asp.net-mvc knockout.js kendo-ui telerik kendo-dropdown