Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically generate table in loop / foreach MVC view

I am writing some very poor code right now and before I even save it I was hoping to get some input on improving it. I am trying to build an html table with three cells to every row. If the collection has 5 items then that should render as two rows.

The code I have written so far I can see is not very robust and will require constant maintenance but I am unsure of other tools / methods for accomplishing the task.

<table>
    @foreach (VideosModel item in Model)
    {
        if (cellCount == 0 || cellCount == 3)
        { 
            @Html.Raw("<tr>") 
        }
           <td style="padding:0px 20px;">
                @item.VideoTitle <br />
                <a href="@item.VideoUrl" target="_blank">
                    <img src="../../.../Video.jpg" /> <br />
                </a>
                @item.VideoDescription
                <br />
            </td>

        cellCount++;

        if (cellCount == 3 || cellCount == 6)
        { 
            @Html.Raw("</tr>") 
        }

        if (cellCount > 3) { cellCount = 0; }
    }
</table>
like image 836
GPGVM Avatar asked Jan 12 '23 17:01

GPGVM


1 Answers

You should considering using modulo instead of comparing the values of cellCount to 0, 3 or 6:

<table>
    @foreach (VideosModel item in Model)
    {
        if (cellCount % 3 == 0)
        { 
            @:<tr>
        }
           <td style="padding:0px 20px;">
                @item.VideoTitle <br />
                <a href="@item.VideoUrl" target="_blank">
                    <img src="../../.../Video.jpg" />
                </a><br />
                @item.VideoDescription
                <br />
            </td>

        cellCount++;

        if (cellCount % 3 == 0)
        { 
            @:</tr>
        }
    }
</table>
like image 84
Cloud SME Avatar answered Jan 20 '23 09:01

Cloud SME