【发布时间】:2016-02-12 22:17:03
【问题描述】:
我将从描述期望的结果开始我的问题:
我想构建一个输入表单以使用淘汰赛 JS 发布到我的 API,但是我要输入的 Entity 对象具有外键,因此我需要为外表中的所有选项提供一个选择选项。
课程视图模型
var lessonRegisterViewModel;
function Lesson(id, name, teacher, room, subject, startTime, endTime) {
var self = this;
self.Id = ko.observable(id);
self.Name = ko.observable(name);
self.Teacher = ko.observable(teacher);
self.Room = ko.observable(room);
self.Subject = ko.observable(subject);
self.StartTime = ko.observable(startTime);
self.EndTime = ko.observable(endTime);
self.addLesson = function() {
var dataObject = ko.toJSON(this);
$.ajax({
url: '/api/Lessons',
type: 'post',
data: dataObject,
contentType: 'application/json',
success: function(data) {
lessonRegisterViewModel.lessonListViewModel.lessons.push(new Lesson(data.Id, data.Name, data.Teacher, data.Room, data.Subject, data.StartTime, data.EndTime));
self.Id(null);
self.Name('');
self.Teacher('');
self.Room('');
self.Subject('');
self.StartTime('');
self.EndTime('');
}
});
}
}
function LessonList() {
var self = this;
self.lessons = ko.observableArray([]);
self.getLessons = function() {
self.lessons.removeAll();
$.getJSON('/api/Lessons', function(data) {
$.each(data, function(key, value) {
self.lessons.push(new Lesson(value.id, value.name, value.teacher, value.room, value.subject, value.startTime, value.endTime));
console.log(self);
});
});
};
self.removeLesson = function(lesson) {
$.ajax({
url: '/api/Lessons/' + lesson.Id(),
type: 'delete',
contentType: 'application/json',
success: function() {
self.lessons.remove(lesson);
}
});
}
}
lessonRegisterViewModel = {
addLessonViewModel: new Lesson(),
lessonListViewModel: new LessonList()
};
$(document).ready(function() {
// bind view model to referring view
ko.applyBindings(lessonRegisterViewModel);
// load lesson data
lessonRegisterViewModel.lessonListViewModel.getLessons();
});
我们得到的 JSON 示例:
[
{
"id":1,
"name":"Lesson 1",
"teacher":{
"id":3,
"firstName":"Sophie",
"lastName":"Adams",
"emailAddress":"teacher3@foo.com"
},
"classroom":{
"id":1,
"name":"Great Hall"
},
"subject":{
"id":4,
"name":"jQuery"
},
"startTime":"2016-02-10T09:30:00",
"endTime":"2016-02-10T10:30:00"
},
{
"id":2,
"name":"Lesson 2",
"teacher":{
"id":4,
"firstName":"Tristan",
"lastName":"Sanchez",
"emailAddress":"teacher4@foo.com"
},
"classroom":{
"id":2,
"name":"Room 1A"
},
"subject":{
"id":3,
"name":"SQL"
},
"startTime":"2016-02-10T09:00:00",
"endTime":"2016-02-10T10:30:00"
}
]
所以基本上我是在插入一个课程,其中包括
名称
老师
房间
主题
开始时间
结束时间
我需要离开,并为数据库中的所有教师提供下拉列表,我还需要为房间和科目执行此操作。我为每个单独的实体都有工作视图模型,没有依赖关系,所以我可以在物理上完成教师、房间和主题的所有 CRUD。
欢迎任何关于如何实施的建议。
【问题讨论】:
-
您将需要一个数组(可能是可观察的)来存储您想要下拉的每一项内容。所以所有教师的列表,所有房间的列表,所有科目的列表。你能明白吗?
-
@RoyJ 如何将其构建到该视图模型中?
-
lessonRegisterViewModel.teachers: ko.observableArray()似乎是合理的。
标签: javascript jquery angularjs ajax knockout.js