gpt4 book ai didi

javascript - 使用数据模型中的 knockout 填充选择下拉列表

转载 作者:行者123 更新时间:2023-12-03 09:09:28 25 4
gpt4 key购买 nike

使用 Knockout.js 使用数据模型中的项目填充简单的下拉列表

<select name="selectCourseArea" class="form-control" data-bind="value: typeid"></select>

此时,我只是尝试将数据库中的任何内容放入下拉列表中,但没有成功。我不是代码的原作者,所以我试图在没有任何先验知识或使用 knockout 的情况下了解发生了什么。我需要在哪里将数据库信息从模型加载到 Controller 。它如何获得Knockout代码以进入 View ?

var CourseViewModel = function (courseIn) {
var self = this;
if (courseIn === undefined) {
courseIn = {};
}

self.id = courseIn.Id;
self.name = ko.observable(courseIn.Name);
self.postalCode = ko.observable(courseIn.PostalCode);
self.city = ko.observable(courseIn.City);
self.province = ko.observable(courseIn.Province);
self.courseId = ko.observable(courseIn.CourseId);
self.courseAreas = ko.observableArray();

$.each(courseIn.CourseAreas, function(index, courseArea) {
self.courseAreas.push(new CourseAreaViewModel(courseArea));
});

self.newCourseArea = function () {
var newArea = true;
$.each(self.courseAreas(), function (index, obj) {
console.log(obj.name());
if ((obj.name() === undefined || obj.name() === null) || (obj.acreage() === null || obj.acreage() === 0)) {
newArea = false;
}
});

console.log(newArea);
if (newArea) {
$.ajax("/CourseArea/Add", {
data: {
courseId: self.id
},
dataType: "json",
method: "post"
}).done(function(newCourseArea) {
console.log(newCourseArea);
self.courseAreas.push(new CourseAreaViewModel(newCourseArea));
});
} else {
alert("Please fill in the course area name and acreage before adding another!");
}

}

self.deleteCourseArea = function (courseArea) {
if (confirm("Are you sure you wish to delete this course area?")) {
$.ajax("/CourseArea/Delete/" + courseArea.id, {
method: "post",
dataType:"json"
}).done(function (feedback) {
if (feedback.Success) {
self.courseAreas.remove(courseArea);
}
alert(feedback.Message);
});
}
}
}

var CourseAreaViewModel = function(courseAreaIn) {
var self = this;
if (courseAreaIn === undefined) {
courseAreaIn = {};
}
self.id = courseAreaIn.Id;
self.name = ko.observable(courseAreaIn.Name);
self.acreage = ko.observable(courseAreaIn.Acreage);
self.goals = ko.observable(courseAreaIn.Goals);
self.typeid = ko.observableArray(courseAreaIn.typeid);
}

最佳答案

您需要将courseAreas绑定(bind)到选择的选项,并且由于它由对象组成,因此您需要为文本和值组件指定键:

<select name="selectCourseArea" class="form-control" data-bind="options: courseAreas, optionsText: 'name', optionsValue: 'id', value: typeid"></select>

关于javascript - 使用数据模型中的 knockout 填充选择下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32124376/

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