MVC + EF Code First多对多关系:使用复选框创建视图

时间:2012-07-16 19:11:11

标签: asp.net-mvc asp.net-mvc-3 entity-framework razor many-to-many

我是MVC + EF Code First的新手,对于多对多关系有一些疑问。

我创建了两个具有多对多关系的表(userprofile和courses)。 听起来很简单,但对我来说非常复杂:

我希望看到“userprofile”的“创建”视图,其中包含每个“课程”现有选项的复选框,并且能够将其保存到相应的数据库。

我一直在阅读并寻找示例,但我没有解决这个问题(或者找到关于这个特殊需求的任何相关信息(我发现类似的事情不适用)

我已经看过这篇文章,但它不是关于创建而不是使用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; }

}

创建控制器:

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

关于视图,我希望只有'@foreach'循环来生成dropbox。

1 个答案:

答案 0 :(得分:2)

你在另一篇我已经回答过的帖子中问过几乎同样的问题。我已经逐步制定了如何做到这一点,这样你就不会出错:)

Saving many to many relationship data on MVC Create View