我有以下代码:
@foreach (Content topic in Model.Topics)
{
if (topic.RowKey.Substring(2, 2) == "00")
{
<h3>@topic.RowKey.Substring(0, 2).TrimStart('0') - @Html.Raw(topic.Title)</h3>
}
else
{
<p>@String.Format("{0}.{1}",topic.RowKey.Substring(0, 2).TrimStart('0'),topic.RowKey.Substring(2, 2).TrimStart('0').PadLeft(1, '0')) - @Html.Raw(topic.Title)</p>
}
}
我的输入数据(topic.RowKey 的值)如下所示:
0100 <- This is topic 1
0101 <- This is topic 1.1
0102 <- This is topic 1.2
0103 <- This is topic 1.3
0200 <- This is topic 2
0201 <- This is topic 2.1
etc....
这行得通,但我真正想做的是每次 RowKey 的前两位数更改时都有一个 h3 标题,然后在然后和下一个 h3 标题之间我想要一个无序列表,而不仅仅是 <p>xxx</p>
.我尝试了很多不同的组合,但没有任何效果。这甚至可能与 Razor 有关吗?我遇到的大问题是如何让 <ul>
和 </ul>
正确显示?我知道我可以在 <ul>
之后放置一个 <h3>
,但是如何放置 </ul>
?
最佳答案
未在 razor 中检查,这里或那里可能缺少 @,但是...
@var groupedTopics = Model.Topics.GroupBy(t => t.RowKey.Substring(0, 2));
@foreach (var group in groupedTopics) {
var firstTopic = group.First();
<h3>@firstTopic.RowKey.Substring(0, 2).TrimStart('0') - @Html.row(firstTopic.Title)</h3>
<ul>
@foreach (var topic in group.Skip(1)) {
<li>@String.Format("{0}.{1}",topic.RowKey.Substring(0, 2).TrimStart('0'),topic.RowKey.Substring(2, 2).TrimStart('0').PadLeft(1, '0')) - @Html.Raw(topic.Title)</li>
}
</ul>
}
关于asp.net-mvc - 如何使无序列表出现在 MVC3 Razor 的 foreach 循环中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10952578/