Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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) {
    <tdstyle="width:240px;margin-left:30px; margin-right:30px;"><imgsrc="@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

Solution 2:

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

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

   if(count%3==0) 
   { 
     **
     trclose 
     tr
     **
   } 
}  
</tr></table></div> 
} 

Solution 3:

Check this out, this should work for you !!!

<h2>Index</h2><table><tr>
        @{
            var index = 0;
        }

        @foreach (int num in Model)
        {
            if ((index % 10) == 0)
            {
            @Html.Raw("</tr>");
            @Html.Raw("<tr>");


            }
            <td><h2>@num</h2></td>
            index++;
        }
    </tr></table>

Solution 4:

The @christian solution worked for me.I was not sure of "trclose" and "tr" hence posting here the solution that worked for me in razor view.

<table><tr><td><inputtype="checkbox"id="chkAssetCategories" />&nbsp;SELECT ALL</td></tr><tr>
         @{
             var count=0;
            foreach (var item in Model.AssetCategories)
                {
                    <td><inputtype="checkbox"class = "Catgories"id='@item.ID'value ='@item.ID' /><label>@item.Name</label></td>
                    if (count%5 == 0)
                    {
                        @:</tr><tr>
                    }
                    count++;
                }
         }
        </table>

Solution 5:

@{ int counter = 0;}
<div>
    <table>
        @for(int i = 0; i <= (Model.Count - 1) / 3; ++i) {
            <tr>
                 for(int j = 0; j < 3; ++j) {
                      <td style="width:240px;margin-left:30px; margin-right:30px;">
                          @Model[counter]
                      </td>
                      counter++;
                 }
             </tr>
        }
    </table>
</div>

Post a Comment for "Razor View Dynamic Table Rows"