我有一个对象列表,我需要从表中的列表中打印东西,以将功能A与功能B进行比较。
但是,就像现在一样,在进行表格渲染时,A中的所有项目都在一行中,而B中的所有项目都在一行中,而不是列中的A项目和下一个中的B项目列。
我正在做类似的事情。
<div style="display: table;">
@foreach(var OuterItem in Outer) {
<div style="table-row">
@foreach(var InnerItem in OuterItem.SubItems) {
<div style="table-cell">
@Html.Raw(InnerItem.Property)
</div>
}
</div>
}
</div>
哪会产生类似
的东西| A1 | A2 | A3|
| B1 | B2 | B3|
但我正在寻找的是......
| A1 | B2 |
| A2 | B2 |
| A3 | B3 |
有没有办法循环生成该表?
转换数据似乎也是不必要的,但我可能错了。
答案 0 :(得分:0)
我不确定您的Outer
和SubItems
集合的支持结构是什么。如果它们是可索引的并且具有相同数量的SubItems
,那么您可能会执行以下操作:
<div style="display: table;">
@for(var j = 0; j < Outer[0].SubItems.Count; j++) {
<div style="table-row">
@for(var i = 0; i < Outer.Count; i++) {
<div style="table-cell">
@Html.Raw(Outer[i].SubItems[j].Property)
</div>
}
</div>
}
</div>
在小范围内,并且假设您总是至少有一个Outer
项,这应该没问题,但是从性能观点来看,不按顺序访问项目,因为它不是非常(内存)缓存友好
最好保留原来的循环结构,然后使用CSS重新设计HTML,将两列并排放置:
<div id="container">
@for(var j = 0; j < Outer[0].SubItems.Count; j++) {
<div style="tablecolumn">
@for(var i = 0; i < Outer.Count; i++) {
<div class="tablecell">
@Html.Raw(Outer[i].SubItems[j].Property)
</div>
}
</div>
}
<!-- make sure the container layout is displayed correctly by adding a clear fix -->
<div class="clearfix"></div>
</div>
在CSS中设置tablecolumn
和tablecell
的样式,以显示垂直列中的元素。我认为最重要的是确保tablecell
元素都具有相同的高度,以免发生错位。
.tablecolumn {
float: left;
width: 49%;
}
.tablecell {
height: 25px; /* or whatever value you find appropriate */
}