ViewModel在View中查看多个模型

时间:2017-06-09 07:51:03

标签: asp.net asp.net-mvc asp.net-mvc-5

我是ASP.NET MVC的初学者,并尝试使用ViewModel.cs在视图中添加多个模型,但我无法在我的视图中看到Index.cshtml任何人都可以指导我如何才能获得它?

ViewModel.cs

public class ViewModel
    {
        public IEnumerable<ContactLens.Models.manufacturer> manufacturer {get; set;}
        public IEnumerable<ContactLens.Models.brand> brand { get; set; }
    } 

HomeController.cs

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

        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to my demo!";
            ViewModel mymodel = new ViewModel();
            mymodel.manufacturer = db.manufacturers.ToList();
            mymodel.brand = db.brands.ToList();
            return View(mymodel);
        }
     }

Index.cshtml

@model ViewModel        
@{
    ViewBag.Title = "Home Page";
}
     --------
<h3 class="menu_head">Top Manufacturers</h3>
 <ul class="menu">
        @foreach (var manufacturer in Model)
        {
           <li class="item1">
           <a href="#"><img class="arrow-img" src="images/f_menu.png" alt="" /> @manufacturer.man_name </a>
           </li>
        }
</ul>
 <h3 class="menu_head">Top Brands</h3>
  <ul class="menu">
         @foreach (var brand in Model)
         {
           <li class="item1">
           <a href="#"><img class="arrow-img" src="images/f_menu.png" alt="" /> @brand.brand_name </a>
           </li>
         }
</ul>
  -------

由于它导致我在@model ViewModel出现错误,我无法访问Index.cshtml中的模型。

2 个答案:

答案 0 :(得分:2)

应该是

@model [Full Path of Your Model]

所以在你的情况下可能是:

@model [SolutionName].[ModelDirectoryIfAny].[Model]

修改

@{
    ViewBag.Title = "Home Page";
}
     --------
<h3 class="menu_head">Top Manufacturers</h3>
 <ul class="menu">
        @foreach (var manufacturer in Model.manufacturer)
        {

        }
</ul>
 <h3 class="menu_head">Top Brands</h3>
  <ul class="menu">
         @foreach (var brand in Model.brand)
         {

         }
</ul>

答案 1 :(得分:1)

我通过将@model ViewModel替换为

解决了我的问题

@model [SolutionName].[ModelDirectoryIfAny].[Model]

  // some code
@foreach (var manufacturer in Model)
 // some code

@foreach (var brand in Model)

进入

  // some code
@foreach (var manufacturer in Model.manufacturer)
 // some code
@foreach (var brand in Model.brand)

分别在 Index.cshtml