本文介绍了一个视图中的 MVC 多个模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一个视图中访问多个模型.我有 DAL 文件夹和 DbContext.

I want to reach multiple models in one view. I have DAL folder and 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

And HomeController

public class HomeController : Controller
{
   private CvContext db = new CvContext();

   public ActionResult Index()
   {
      return View(db.Links.ToList());
   }
}

索引.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 作为模型中的项目,如链接.谢谢.

How can i reach all models? I will use foreach for item in Model like Links. Thanks.

推荐答案

你应该创建一个视图模型如下:

You should create a view model as follows:

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

然后从您的控制器中根据您的要求填充它们,例如:

Then from your controller populate them as to your requirements, as an example:

   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,您的所有属性都将在其中可用.

Then change the model in your view to FooViewModel and all your properties will be available in there.

@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.

这篇关于一个视图中的 MVC 多个模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 22:36