I need to send data in the form of a list for two different models in my database to a view in an MVC4 project.
Something like this:
Controller:
public ActionResult Index()
{
Entities db = new Entities();
ViewData["Cats"] = db.Cats.toList();
ViewData["Dogs"] = db.Dogs.toList();
return View();
}
View:
@* LIST ONE *@
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.ListOneColOne)
</th>
<th>
@Html.DisplayNameFor(model => model.ListOneColTwo)
</th>
<th>
@Html.DisplayNameFor(model => model.ListOneColThree)
</th>
</tr>
@foreach (var item in @ViewData["Cats"]) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.ListOneColOne)
</td>
<td>
@Html.DisplayFor(modelItem => item.ListOneColTwo)
</td>
<td>
@Html.DisplayFor(modelItem => item.ListOneColThree)
</td>
</tr>
@* LIST TWO *@
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.ListTwoColOne)
</th>
<th>
@Html.DisplayNameFor(model => model.ListTwoColTwo)
</th>
<th>
@Html.DisplayNameFor(model => model.ListTwoColThree)
</th>
</tr>
@foreach (var item in @ViewData["Dogs"]) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.ListTwoColOne)
</td>
<td>
@Html.DisplayFor(modelItem => item.ListTwoColTwo)
</td>
<td>
@Html.DisplayFor(modelItem => item.ListTwoColThree)
</td>
</tr>
The View is to display two list's, one list per model.
I'm unsure as to what the most efficient way to do this is?
Viewmodel?
Viewdata/Viewbag?
Something else?
(Please no third-party suggestions)
UPDATE:
Further I've attempted for over an hour now to implement the answer suggesting a List<T>
Viewmodel without any luck. I believe this is due to the fact that my Viewmodel looks like this:
public class GalleryViewModel
{
public Cat cat { get; set; }
public Dog dog { get; set; }
}
List<String>
rather the actual model type e.g.,public ListA listA { get; set; }
. I'm going to update my initial post to reflect this. – Dag