MVC + EF Code First Many to Many relationship: Create view with checkbox entity-framework many-to-many razor


I'm a newbie with MVC + EF Code First and have some doubts about many to many relationship.

I created 2 tables that has many to many relationship (userprofile and courses). Sounds simple but it got pretty complex for me:

I want to see the "create" view of the "userprofile" with checkboxed for each of the "courses"existent options and being able to save it to corresponding databases.

I've been reading and looking for examples but I didn't get to solved this (or to find any related information about this particular need (I found similar things that didn't apply)

I already saw this article but it's not about the create and not using EF (

public class UserProfile
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Courses>  usercourses { get; set; }

public class Courses
    public int CourseID { get; set; }
    public string CourseDescripcion { get; set; }
    public virtual ICollection<UserProfile> UserProfiles { get; set; } 

 public class UserProfileDBContext : DbContext
    public DbSet<UserProfile> UserProfiles { get; set; }
    public DbSet<Courses> usrCourses{ get; set; }


The Create Controler:

        public ActionResult Create()
        return View();

    public ActionResult Create(UserProfile userprofile)
        if (ModelState.IsValid)
            return RedirectToAction("Index");  
        return View(userprofile);

Regarding the view, I would like to have just the '@foreach' loop for generating the dropboxes.

7/16/2012 7:32:25 PM

Popular Answer

You asked pretty much the same question in another post which I've answered. I've laid out step by step how to do it so you can't go wrong :)

Saving many to many relationship data on MVC Create View

5/23/2017 12:16:20 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow