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

时间:2015-08-20 17:14:39

标签: javascript jquery asp.net-mvc knockout.js

使用Knockout.js

填充数据模型中的项目的简单下拉列表
<select name="selectCourseArea" class="form-control" data-bind="value: typeid"></select>

此时我只是试图从数据库中获取任何内容而没有成功。我不是代码的原始作者,所以我试图了解在没有任何先验知识或使用淘汰赛的情况下发生了什么。我需要将DB信息从模型加载到控制器。如何通过Knockout代码转到视图?

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

1 个答案:

答案 0 :(得分:1)

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

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