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
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
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> 
} 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With