I have a cshtml view linked to a controller for a model for one table in my database, but I need to do a for each loop that references a second model for a second table. Since setting 2 models at the top of the page is not possible foreach (var row in model)
won't work.
what I need is something like this
@model MVCapp.Models.COOKIE
@using MVCapp.Models;
@{
ViewBag.Title = "Update";
;
foreach (var row in IEnumerable<MVCapp.Models.COOKIE_JARS)
{
some code
}
}
Update:
Although that is not allowed because I'm using a type like a variable. So what I am asking is if there is a way to set type:IEnumerable<MVCapp.Models.COOKIE_JARS
to a variable or a second model, Or if there is a completely alternative method to achieve this looping through a second database table that I am trying to attempt.
The best way to do this is to create a ViewModel
, a class that will contain the information of both your models.
You view must never made any logic or get information from your database, this is the goal of the Controller.
So, the idea is that your controller will make the queries, and add the data into your ViewModel
object that will then be sent to the View.
Example :
Your ViewModel:
public class CookieEatersViewModel
{
public IEnumerable<Cookie> Cookies {get; set;}
public IEnumerable<Monster> Monsters {get; set;}
}
Your View:
@model MVCApp.ViewModels.CookieEatersViewModel
<h2>Update</h2>
<p>Use the informations from your ViewModel here</p>
Your controller:
public ActionResult Index()
{
CookieEatersViewModel cevm = new CookieEatersViewModel();
cevm.Cookies = repo.GetCookies();
cevm.Monsters = repo.GetMonsters();
return View(vm);
}