首页 > 解决方案 > 如何使用mvc遍历记录并保存到数据库中

问题描述

我有一个表,其中我的模型类中有三列(id,studentid,courseid)我有 studentid 和 courseid 作为数组,因为在视图中它们是多选下拉列表,现在在我的创建控制器中,我想先循环遍历学生然后分配课程数组中的所有课程,然后在分配所有课程后,我需要转移到下一个学生并分配他所有课程

public ActionResult Create([Bind(Include = "Id,Year_Id,Program_Id,Student_id,Module_Id,Course_Id")]Student_Assigned_courses SAC)
        {
            ViewBag.PopulatePrograms = _IEducation.PopulatePrograms();
            //ViewBag.Block_Id = new SelectList(db.Blocks, "Id", "Name");
            //ViewBag.Course_Category_Id = new SelectList(db.Courses_Category, "Id", "Category_Name");
            //ViewBag.Module_Id = new SelectList(db.Moduels, "Id", "Name");
            //ViewBag.Program_Id = new SelectList(db.Programs, "Id", "Program_Title");
            //ViewBag.Year = new SelectList(db.Years, "Id", "Name");
            //ViewBag.Course_Id = _ITeacherCoruses.PopulateCourses();
            //ViewBag.Teacher_Id = _ITeacherCoruses.PopulateTeachers();
            //ViewBag.Semester_Id = _ITeacherCoruses.PopulateSemsters();
            if (SAC.Student_id != null)
            {
               foreach(var student in SAC.Student_id)
                {

                    for (int i = 0; i < SAC.Course_Id.Length; i++)

                       // SAC.Course_Id = SAC.Course_Id[i] ;
                        db.StudentCoursesAssigned.Add(SAC);
                        if (db.SaveChanges() > 0)
                        {
                            TempData["MessageDesignation"] = "Department Saved Successfully!";


                        }

                }
                return RedirectToAction("Index");
            }
            return View(SAC);
        }

我只给出了三列,但实际上我的表和模型类中有五列。

标签: arraysmodel-view-controllermultiple-columns

解决方案


推荐阅读