Mark Tabor

Mark Tabor

  • 959
  • 1.2k
  • 142.3k

how to save multiple selected values of dropdownlist in mvc

Feb 4 2020 9:23 AM
hi I have a model class in which i have two properties as arrays like student and courses and on view i have multi select dropdown list to select multiple students and multiple courses , Now on post in my controller i am getting the selected values as arrays , but i am confused like when i am looping through all selected values i am saving them into a string or int variable , but i am unable to assign this string or int value to the model object properties as it is of type array below is the code can someone correct this code as i need to loop through the students first and then assign all courses to first student then second students and then so one .
 
public ActionResult Create([Bind(Include = "Id,Year_Id,Program_Id,Student_id,Module_Id,Course_Id")]Student_Assigned_courses SAC)
{
ViewBag.PopulatePrograms = _IEducation.PopulatePrograms();
if (SAC.Student_id != null)
{
foreach(var student in SAC.Student_id)
{
foreach(var course in SAC.Course_Id)
{
Student_Assigned_courses Sa = new Student_Assigned_courses();
for(int i=0;i<SAC.Student_id.Length;i++)
{
string s = SAC.Student_id[i].ToString();
//Sa.Student_id = Convert.ToInt32(SAC.Student_id[i].ToString());
Sa.Course_Id = SAC.Course_Id;
Sa.Module_Id = SAC.Module_Id;
Sa.Year_Id = SAC.Year_Id;
Sa.Program_Id = SAC.Program_Id;
db.StudentCoursesAssigned.Add(Sa);
// Sa.Student_id = SAC.Student_id[i];
}
if (db.SaveChanges() > 0)
{
TempData["MessageDesignation"] = "Department Saved Successfully!";
}
}
}
return RedirectToAction("Index");
}
return View(SAC);
}yellow highlighted line gives error

Answers (16)