Reputation: 397
I am beginner in ASP.NET MVC and trying to add multiple models in view by using ViewModel.cs
but I can't get it in my view Index.cshtml
anyone can guide me how can I get it?
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>
-------
It is showing me an error at @model ViewModel
due to it, I can't access models in Index.cshtml
.
Upvotes: 0
Views: 429
Reputation: 397
I resolved my issue by replacing just @model ViewModel
into
@model [SolutionName].[ModelDirectoryIfAny].[Model]
and
// some code
@foreach (var manufacturer in Model)
// some code
@foreach (var brand in Model)
into
// some code
@foreach (var manufacturer in Model.manufacturer)
// some code
@foreach (var brand in Model.brand)
respectively in Index.cshtml
Upvotes: 0
Reputation: 967
it should be
@model [Full Path of Your Model]
So in your case it might be:
@model [SolutionName].[ModelDirectoryIfAny].[Model]
Edit
@{
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>
Upvotes: 1