一个视图中的MVC多个模型
我想在一个视图中访问多个模型。 我有DAL文件夹和DbContext。
class CvContext : DbContext { public CvContext() : base("CvContext") { } public DbSet Links { get; set; } public DbSet Abouts { get; set; } public DbSet Portfolios { get; set; } public DbSet Skills { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Remove(); } }
和HomeController
public class HomeController : Controller { private CvContext db = new CvContext(); public ActionResult Index() { return View(db.Links.ToList()); } }
Index.cshtml
@model IEnumerable
我怎样才能到达所有型号? 我会在模型链接中使用foreach for item。 谢谢。
您应该创建一个视图模型,如下所示:
public class FooViewModel { public IEnumerable Links { get; set; } public IEnumerable Abouts { get; set; } public IEnumerable Portfolios { get; set; } public IEnumerable Skills { get; set; } }
然后从您的控制器填充它们以满足您的要求,例如:
public ActionResult Index() { var model = new FooViewModel(); model.Links = db.Links.ToList(); model.Abouts = db.Abouts.ToList(); model.Portfolios = db.Portfolios.ToList(); model.Skills = db.Skills.ToList(); return View(model); }
然后将视图中的模型更改为FooViewModel
并在那里提供所有属性。
@model FooViewModel @foreach (var item in Model.Links) { - @item
}
@foreach (var item in Model.Links) { - @item
}
// ....etc, obviously change the outputs as needed.
//suppose you have two Models public class student { public int Id public string Name{get;set;} } public class class { public int Id public string Name{get;set;} } // Now combine these two class Model in single Model for example: public class Mixmodel { public Student student {get;set;} public Class class {get;set;} } //here is the Home controller of the Index view @model projectName.MixModel @foreach(var item in Model.class) { @html.displayfor(item.class.Name) } @foreach(var item in Model.student) { @html.displayfor(item.student.Name) }