First,
Your models should be something like below.
public class Student
{
public int StudentID { get; set; }
public string Name { get; set; }
public virtual ICollection<AssignedCourseData> Courses { get; set; }
}
public class CourseViewModel
{
public int CourseID { get; set; }
public string CourseDescripcion { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
And
Your create/update actions something like this
[HttpPost]
public ActionResult Create(Student student)
{
if (ModelState.IsValid)
{
var student = new Student { Name = student.Name };
AddOrUpdateCourses(student, student.Courses);
db.Student.Add(student);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(userProfileViewModel);
}
private void AddOrUpdateCourses(Student student, IEnumerable<AssignedCourseData> assignedCourses)
{
if (assignedCourses != null)
{
foreach (var assignedCourse in assignedCourses)
{
if (assignedCourse.Assigned)
{
var course = new Course { CourseID = assignedCourse.CourseID };
db.Courses.Attach(course);
student.Courses.Add(course);
}
}
}
}
More can be found here...
http://codenodes.wordpress.com/2013/01/13/saving-many-to-many-data-in-mvc4-and-ef-4-1-code-first-part-1/[
^]