5
我需要将数据库中两个不同模型的列表形式的数据发送到MVC4项目中的视图。MVC4 ViewBag或ViewModel或?
事情是这样的:
控制器:
public ActionResult Index()
{
Entities db = new Entities();
ViewData["Cats"] = db.Cats.toList();
ViewData["Dogs"] = db.Dogs.toList();
return 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>
观是显示两个列表的,一个列表每个型号。
我不确定最有效的方法是什么?
Viewmodel?
Viewdata/Viewbag?
还有其他的东西吗?
(请没有第三方的建议)
UPDATE:
而且我已经尝试了一个多小时,现在实行的答案提示有List<T>
视图模型没有任何的运气。我相信这是由于这样的事实,我的视图模型看起来像这样:
public class GalleryViewModel
{
public Cat cat { get; set; }
public Dog dog { get; set; }
}
感谢@row我一直试图让这个工作,但我似乎无法弄清楚。显然问题是我的ViewModel不是由'List'组成的,而是实际的模型类型,例如'public ListA listA {get;组; }'。我要更新我的初始文章以反映这一点。 –
2013-05-01 07:01:23
花了一段时间,但我明白了!谢谢罗文。 – 2013-05-01 08:13:29