MVC + EF Code First Many to Many relationship: Create view with checkbox

asp.net-mvc asp.net-mvc-3 entity-framework many-to-many razor

Question

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 (http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/updating-related-data-with-the-entity-framework-in-an-asp-net-mvc-application)

public class UserProfile
{
    [Key]
    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();
    } 

    [HttpPost]
    public ActionResult Create(UserProfile userprofile)
    {
        if (ModelState.IsValid)
        {
            db.UserProfiles.Add(userprofile);
            db.SaveChanges();
            return RedirectToAction("Index");  
        }
        return View(userprofile);
    }

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

1
3
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

2
5/23/2017 12:16:20 PM


Related Questions





Related

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