我想在一个视图中覆盖多个模型。我有DAL文件夹和DbContext。
class CvContext : DbContext
{
public CvContext() : base("CvContext")
{
}
public DbSet<LinkModel> Links { get; set; }
public DbSet<AboutModel> Abouts { get; set; }
public DbSet<PortfolioModel> Portfolios { get; set; }
public DbSet<SkillModel> Skills { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
和HomeController
public class HomeController : Controller
{
private CvContext db = new CvContext();
public ActionResult Index()
{
return View(db.Links.ToList());
}
}
Index.cshtml
@model IEnumerable<MvcCv.Models.LinkModel>
<ul>
@foreach (var item in Model)
{
<li>
<a href="@Html.DisplayFor(modelItem => item.LinkUrl)">
@Html.DisplayFor(modelItem => item.LinkName)
<span class="icon"></span>
<span class="menu-icon">
<img src="@Url.Content(item.LinkImage)" alt="" />
</span>
</a>
</li>
}
</ul>
我如何覆盖所有型号?我会在模型链接中使用foreach for item。感谢。
答案 0 :(得分:12)
您应该按如下方式创建视图模型:
public class FooViewModel
{
public IEnumerable<LinkModel> Links { get; set; }
public IEnumerable<AboutModel> Abouts { get; set; }
public IEnumerable<PortfolioModel> Portfolios { get; set; }
public IEnumerable<SkillModel> 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
<ul>
@foreach (var item in Model.Links)
{
<li>
@item
</li>
}
</ul>
<ul>
@foreach (var item in Model.Links)
{
<li>
@item
</li>
}
</ul>
// ....etc, obviously change the outputs as needed.
答案 1 :(得分:0)
//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)
}