3

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

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.