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 new to MVC and EF Code First and am unsure how many to many relationships work.

Two tables I made have many-to-many relationships (userprofile and courses). Although it seems easy, I found it to be rather difficult:

I want to be able to construct a "userprofile" with checkboxes for all of the available "courses" and save it to the appropriate databases.

I've tried reading and seeking for examples, but I haven't been able to solve this or locate any knowledge relevant to my specific requirement (I discovered things that were similar but didn't apply).

Although I've previously seen it, this article (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) is not about creating and is not utilizing EF.

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; }

}

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);
    }

I would want to have simply the "@foreach" loop for creating the dropboxes in the view.

1
3
7/16/2012 7:32:25 PM

Popular Answer

In a different thread, you essentially posed the same question, to which I responded. You can't go wrong since I have provided step-by-step instructions:)

storing data from many to many relationships in 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