【问题标题】:Foreach loop for tables in MVC4MVC4 中表的 Foreach 循环
【发布时间】:2013-08-26 01:09:01
【问题描述】:

我正在使用 c# 在 MVC4 中做我的项目。我的模型中有一个 IEnumerable 列表。我使用以下循环在我的视图中列出它。

       <table id="memberlist">
       <tbody>
        @foreach(var item in Model)
         {
          <tr>
             <td>Rtn. @item.Mem_NA<br />(@item.Mem_Occ)</td>
          </tr>
         }
       </tbody>
       </table>

其实我想要下表中的输出

 <table id="memberlist">
       <tbody>
          <tr>
             <td>Rtn.item.Mem_NA1<br />(item.Mem_Occ1)</td>
             <td>Rtn.item.Mem_NA2<br />(item.Mem_Occ2)</td>
             <td>Rtn.item.Mem_NA3<br />(item.Mem_Occ3)</td>
          </tr>
          <tr>
             <td>Rtn.item.Mem_NA4<br />(item.Mem_Occ4)</td>
             <td>Rtn.item.Mem_NA5<br />(item.Mem_Occ5)</td>
             <td>Rtn.item.Mem_NA6<br />(item.Mem_Occ6)</td>
          </tr>
       </tbody>
       </table>

是否可以使用 foreach 循环生成上述表格。或者更好地使用 div 而不是 table。请帮帮我

【问题讨论】:

  • 首先完全可以做到这一点。其次,你不应该这样做。考虑使用&lt;div /&gt; 使布局“流动”。用 div 创建的“表格”将随窗口调整大小。
  • 你的问题是用 DIV 代替 Table 还是 For Each 在 MVC 中创建表格布局?
  • 请参阅本教程。 css.maxdesign.com.au/floatutorial

标签: c# html asp.net-mvc-4


【解决方案1】:

首先,完全可以做到这一点。其次,你不应该这样做。考虑使用&lt;div /&gt; 使布局“流动”。用 div 创建的“表格”会随窗口调整大小。

       @{
           int groupings = 3;
           var grouped = Model.Select((x,i) => new { x, i = i / groupings  })
                         .GroupBy(x => x.i, x => x.x);
       }

       <table id="memberlist">
       <tbody>
        @foreach(var items in grouped)
         {
          <tr>
             @foreach(var item in items)
             {
                 <td>Rtn. @item.Mem_NA<br />(@item.Mem_Occ)</td>
             }
          </tr>
         }
       </tbody>
       </table>

使用 div 你会...

    @foreach(var item in Model)
     {
         <div style="float:left;">Rtn. @item.Mem_NA<br />(@item.Mem_Occ)</div>
     }

【讨论】:

    【解决方案2】:

    谢谢大家,我有另一种方式

    @{
     int total = 0; 
    }
    <table id="memberlist">
    <tbody>
        @foreach(var item in Model)
        {
            if( total % 4 == 0 ){
            @:<tr>
            }
            <td>Rtn. @item.Mem_NA<br />(@item.Mem_Occ)</td>
            if( total+1 % 5 == 0 ){
            @:</tr>
            }
            total++;
        }
    </tbody>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-28
      • 1970-01-01
      • 1970-01-01
      • 2016-09-26
      • 2012-07-19
      • 2019-11-17
      • 1970-01-01
      相关资源
      最近更新 更多