id.*_*.ot 5 viewmodel viewbag asp.net-mvc-4
我需要以数据库中两个不同模型的列表形式将数据发送到MVC4项目中的视图.
像这样的东西:
控制器:
public ActionResult Index()
{
Entities db = new Entities();
ViewData["Cats"] = db.Cats.toList();
ViewData["Dogs"] = db.Dogs.toList();
return View();
}
Run Code Online (Sandbox Code Playgroud)
查看:
@* 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>
Run Code Online (Sandbox Code Playgroud)
视图将显示两个列表,每个模型一个列表.
我不确定最有效的方法是什么?
视图模型?
可视数据/ Viewbag?
别的什么?
(请不要第三方建议)
更新:
此外,我已经尝试了一个多小时来实现建议List<T>Viewmodel没有任何运气的答案.我相信这是因为我的Viewmodel看起来像这样:
public class GalleryViewModel
{
public Cat cat { get; set; }
public Dog dog { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
尝试解释您的问题和您的目标,因此我们(特别)知道您正在尝试做什么.
我认为这意味着您有两个列表,并且您希望将它们发送到视图.一种方法是将两个列表放入模型并将模型发送到视图,但您似乎已经指定您已经有两个模型,因此我将采用该假设.
调节器
public ActionResult Index()
{
ModelA myModelA = new ModelA();
ModelB myModelB = new ModelB();
IndexViewModel viewModel = new IndexViewModel();
viewModel.myModelA = myModelA;
viewModel.myModelB = myModelB;
return View(viewModel);
}
Run Code Online (Sandbox Code Playgroud)
查看模型
public class IndexViewModel
{
public ModelA myModelA { get; set; }
public ModelB myModelB { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
模型
public class ModelA
{
public List<String> ListA { get; set; }
}
public class ModelB
{
public List<String> ListB { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
视图
@model IndexViewModel
@foreach (String item in model.myModelA)
{
@item.ToString()
}
Run Code Online (Sandbox Code Playgroud)
(抱歉,如果我的C#生锈了)
| 归档时间: |
|
| 查看次数: |
6453 次 |
| 最近记录: |