我是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
中的模型。
答案 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
中