多个模型到一个视图中
本文关键字:一个 视图 模型 | 更新日期: 2023-09-27 18:30:51
我在这里看到过这个问题,但它似乎与我的情况不同。 我可能错了,但我们拭目以待。
现在我正在MVC3(C#)中创建一个博客类型的网站,我目前可以创建,编辑,删除等博客,一切正常。 我正在使用代码优先 EF,所以我不知道这有多重要。
我有一个博客文章模型如下:
public class BlogPost
{
public int id { get; set; }
public string Title { get; set; }
public DateTime DateCreated { get; set; }
public ICollection<Topic> Topics { get; set; }
public string Content { get; set; }
public ICollection<Comment> Comments { get; set; }
}
和主题模型(每篇博客文章可以有多个主题)
public class Topic
{
public int id { get; set; }
public string Name { get; set; }
public int PostId { get; set; }
// navigation back to parent
public BlogPost Post { get; set; }
}
然后是我的 DbContext 继承模型,其中包含我的所有模型:
public class MyModel : DbContext
{
public DbSet<BlogPost> Posts { get; set; }
public DbSet<Comment> Comments { get; set; }
public DbSet<Topic> Topics { get; set; }
public DbSet<AdminComment> AdminComments { get; set; }
public DbSet<Bug> Bugs { get; set; }
}
目前,博客控制器正在使用默认脚手架来创建/编辑/删除/详细信息
private MyModel db = new MyModel();
//
// GET: /Admin/Blog/
public ViewResult Index()
{
return View(db.Posts.ToList());
}
我该怎么做才能传入其他模型,所以在这个列表中,它将显示与帖子相关的所有主题,并添加一个创建以向您当前正在创建的帖子添加主题?
创建一个外部对象,该对象具有您希望视图能够看到的属性,并将新对象用作模型。你几乎已经这样做了。只需将您的控制器更改为以下内容:
public ViewResult Index()
{
return View(db);
}
现在,视图可以访问所有内容。