4

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>
2
  • For starters, there is no need to have the <tr> wrapped in an @Html.Raw() Commented Dec 10, 2013 at 22:52
  • When I don't have it wrapped in the raw I get the error that if then closing brace not found. Such as described here: forums.asp.net/t/1654550.aspx Commented Dec 10, 2013 at 22:56

1 Answer 1

9

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>
Sign up to request clarification or add additional context in comments.

2 Comments

Is the @: shorthand for something? I didn't know about it and Googling @: or MVC @: returns nada.
Same thing as <text><tr></text> weblogs.asp.net/scottgu/archive/2010/12/15/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.