KnockoutJS - 嵌套的JSON对象

时间:2016-02-11 15:33:30

标签: javascript c# json knockout.js asp.net-web-api2

我正在努力扩展我对KnockoutJS的了解(我对此有很高的了解)。我正在使用Web API构建一个C#项目来处理数据访问 - >表示层,但是我的视图模型遇到了一些问题,我知道这是我做错的事情,所以希望有人可以帮我解释我做了什么?

我们将从数据库中获取“课程”,并以JSON格式返回。这是班级:

Lesson.cs

using System;

namespace TestApplication.Model
{
    public class Lesson
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public virtual Teacher Teacher { get; set; }
        public virtual Classroom Classroom { get; set; }
        public virtual Subject Subject { get; set; }
        public virtual DateTime StartTime { get; set; }
        public virtual DateTime EndTime { get; set; }
    }
}

如果我直接进入Web API路线,这是返回的课程:

Lessons.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"
}
]

最后,这是我的KnockoutModel:

LessonsViewModel.js

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

课程数量,名称,开始和结束时间的绑定工作正常,它只是嵌套对象以及我如何映射这些以获取我需要的值来自这些类是痛苦,但任何一般改进/建设性批评也欢迎。

1 个答案:

答案 0 :(得分:1)

您可以为嵌套对象定义单独的模型:

function Lesson(id, name, teacher, room, subject, startTime, endTime) {
    var self = this;
    self.Id = ko.observable(id);
    self.Name = ko.observable(name);
    self.Teacher = new Teacher(teacher);
    self.Room = new Classroom(room);
    self.Subject = new Subject(subject);
    self.StartTime = ko.observable(startTime);
    self.EndTime = ko.observable(endTime);

    //....
}

function Teacher(t) {
    var self = this;
    self.Id = ko.observable(t.id);
    self.FirstName = ko.observable(t.firstName);
    self.LastName = ko.observable(t.lastName);
    self.EmailAddress = ko.observable(t.emailAddress);
}

function Classroom(c) {
    var self = this;
    self.Id = ko.observable(c.id);
    self.Name = ko.observable(c.name);
}

function Subject(s) {
    var self = this;
    self.Id = ko.observable(s.id);
    self.Name = ko.observable(s.name);
}