Foreach loop for tables in MVC4

2020-03-30 10:11发布

问题:

I am doing my project in MVC4 using c#. I have an IEnumerable list in my model. I use the following loop to list that in my view.

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

Actually i want the output like in the following 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>

Is that possible for generating a table like above using a foreach loop. or is better using the div instead of table. Please help me

回答1:

Firstly it is entirely possible to do this. Secondly, you should not do this. Consider using <div /> to make the layout "flow". The "table" created with divs will resize with the window then.

       @{
           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>

Using divs you would...

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


回答2:

Thank you everybody i got another way

@{
 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>