Jim Sherwood
Jim Sherwood

Reputation: 3

Creating a new row every 4 or 5 columns in C# razor code

I saw a way to do this in php, but I'm using razor code. I need to insert a close row and an open row tag every 4 loops. But the main loop I'm using is a foreach which doesn't really give me a good variable to use mod on. Here is what I have. Can you give me a quick solution? I'm sure it's simple. This is what I have:

  <tbody>
        <tr align="center">
            @foreach (var item in Model)
            { @for (int loops = 1; loops < 6; loops++)
                {   
                <td>
                    <img src="@Html.DisplayFor(modelItem => item.PicUrl)" height="100" /><br />
                    <b>@Html.DisplayFor(modelItem => item.Name)</b><br />
                    @Html.DisplayFor(modelItem => item.Description)<br />
                    <a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
                    <a asp-action="Details" asp-route-id="@item.Id">Details</a> |
                    <a asp-action="Delete" asp-route-id="@item.Id">Delete</a>
                </td>
                }

            }
        </tr>
    </tbody>

Unfortunately, as you might imagine, this code simply puts 5 of the same photo before it loads 5 of the next photo, and all in a single row across.

Upvotes: 0

Views: 677

Answers (1)

Saharsh
Saharsh

Reputation: 760

Updated with counter and mod

@{int counter = 0;}
<tbody>
    <tr align="center">
        @foreach (var item in Model)
        {
            <td>
                <img src="@Html.DisplayFor(modelItem => item.PicUrl)" height="100" /><br />
                <b>@Html.DisplayFor(modelItem => item.Name)</b><br />
                @Html.DisplayFor(modelItem => item.Description)<br />
                <a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
                <a asp-action="Details" asp-route-id="@item.Id">Details</a> |
                <a asp-action="Delete" asp-route-id="@item.Id">Delete</a>
            </td>
            counter++;
            if (counter % 5 == 0)
            {
                @:</tr><tr>
            }
        }
    </tr>
</tbody>

I think counter % 5 logic will need some attention to make sure it's working as expected.

Upvotes: 3

Related Questions