public ActionResult BuildTimetable(int?TermId) { if (TermId == null) { return(RedirectToAction("ChooseTermForTimetable")); } int termId = TermId.Value; int studentId = ((Student)Session["student"]).StudentId; if (!CanEnroll(studentId, termId)) { return(RedirectToAction("RegistrationStatus")); } List <EnrollmentOption> enrollmentOptions = dao.GetEnrollmentOptions(studentId, termId); List <TermDisplay> terms = new List <TermDisplay>(); TermDisplay currentTerm = null; CourseDisplay currentCourse = null; int prevTermId = 0, prevCourseId = 0; foreach (EnrollmentOption o in enrollmentOptions) { if (prevTermId != o.ProgramSemesterId) { // new term, new course prevTermId = o.ProgramSemesterId; prevCourseId = o.CourseId; currentTerm = new TermDisplay() { ProgramSemesterName = o.ProgramSemesterName, Courses = new List <CourseDisplay>(), Electives = new List <ElectiveDisplay>() }; terms.Add(currentTerm); currentCourse = AddCourseToTerm(o, currentTerm); } else if (prevCourseId != o.CourseId) { // same term, new course prevCourseId = o.CourseId; currentCourse = AddCourseToTerm(o, currentTerm); } else { // same course, another section AddSectionToCourse(o, currentCourse); } } ViewBag.JSONString = JsonConvert.SerializeObject(enrollmentOptions); TimetableBuilder timetableBuilder = new TimetableBuilder() { Terms = terms, TermId = termId }; return(View(timetableBuilder)); }