Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Razor View dynamic table rows

I want have a table in my view that is going to put 3 elements from my Model in each row. So the way I was going to do this is to loop through the model and inside of the foreach loop do a check on a count variable I have set up. If count mod 3 == 0 I would do something like </tr><tr> to start a new row. This isn't working the way I want it to because I would have a } following the <tr>. So basically my question is, how would I create a dynamic table inside of a razor view based on the elements in the model where each row has 3 items?

@{
int count = 0;
<div>
<table>
<tr>
@foreach (var drawing in Model)
{
   <td style="width:240px;margin-left:30px; margin-right:30px;">
   <img src="@Url.Action("GetImage", "Home", new { id = drawing.drw_ID })" alt="drawing" /> 
   </td>
   count++;
   if(count%3==0)
   {
      </tr>
      <tr>
   }
} 
</tr>
</table>
</div>
}

Maybe there is a much easier way of doing this that I am not thinking of

like image 540
esastincy Avatar asked Feb 08 '12 17:02

esastincy


2 Answers

How about using two loops - this will make your document be setup much more nicely and make it a bit more readable. Also, it takes care of the problems that occur if the number of rows is not divisible by three:

<div>
<table>
@for(int i = 0; i <= (Model.Count - 1) / 3; ++i) {
  <tr>
  for(int j = 0; j < 3 && i + j < Model.Count; ++j) {
    <td style="width:240px;margin-left:30px; margin-right:30px;">
      <img src="@Url.Action("GetImage", "Home", new { id = Model[i + j].drw_ID })" alt="drawing" /> 
    </td>
   }
   </tr>
}
</table>
</div>

Edited to reflect your pasted code. Note, this assumes the model implements IList or an array

like image 191
eouw0o83hf Avatar answered Nov 14 '22 21:11

eouw0o83hf


Maybee this is the solution you are looking for works for me

 @{ 
int count = 0; 
**
var tr = new HtmlString("<tr>");
var trclose = new HtmlString("</tr>");
**
<div> 
<table> 
<tr> 
@foreach (var drawing in Model) 
{ 
   <td style="width:240px;margin-left:30px; margin-right:30px;"> 
   <img src="@Url.Action("GetImage", "Home", new { id = drawing.drw_ID })" alt="drawing" />  
   </td> 
   count++; 

   if(count%3==0) 
   { 
     **
     trclose 
     tr
     **
   } 
}  
</tr> 
</table> 
</div> 
} 
like image 29
Christian Avatar answered Nov 14 '22 22:11

Christian