【发布时间】:2017-09-03 11:21:09
【问题描述】:
给定以下格式的字典,我想以如下所示的格式输出:
public IActionResult Index()
{
var model = new Dictionary<string, List<MyModel>>
{
{
"Heading1",
new List<MyModel>()
{
new MyModel() {MyKey = "Foo", MyValue = "Value1"},
new MyModel() {MyKey = "Bar", MyValue = "Value2"},
new MyModel() {MyKey = "Baz", MyValue = "Value3"}
}
},
{
"Heading2",
new List<MyModel>()
{
new MyModel() {MyKey = "Foo", MyValue = "Value4"},
new MyModel() {MyKey = "Bar", MyValue = "Value5"}
}
},
{
"Heading3",
new List<MyModel>()
{
new MyModel() {MyKey = "Foo", MyValue = "Value6"},
new MyModel() {MyKey = "Baz", MyValue = "Value7"}
}
}
};
return View(model);
}
MyModel 只是一个简单的类:
public class MyModel
{
public string MyKey { get; set; }
public string MyValue { get; set; }
}
我想按以下格式输出信息:
但是目前我在视图中尝试的内容显示不正确:
@model Dictionary<string, List<MyModel>>
@{
ViewData["Title"] = "Index";
}
<h2>Results</h2>
<table class="table table-striped">
<thead>
<tr>
@foreach (var item in Model.Keys)
{
<th>@item</th>
}
</tr>
</thead>
<tbody>
@foreach (var list in Model.Values)
{
<tr>
@foreach (var item in list)
{
<td>@item.MyKey</td>
<td>@item.MyValue</td>
}
</tr>
}
</tbody>
</table>
如何以所需的格式显示数据?
【问题讨论】:
-
您的
Dictionary<string, List<MyModel>>属性与您要在视图中显示的内容完全没有关系。您需要一个类似于this answer 的视图模型 -
你一定要用字典吗?
-
我也可以用这种方式给你一个解决方案,但字典并不是要以这种方式使用的,我建议一个类列表并在上面使用 LINQ
标签: c# asp.net-mvc dictionary razor asp.net-core