Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
144 views
in Technique[技术] by (71.8m points)

c# - MVC Multiple Models in One View

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

And 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>

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...