Sumudu De Zoysa
Sumudu De Zoysa

Reputation: 253

Display records in table with fixed number of columns

<table>
@{var counter = 1; }
<tr>
    @foreach (var item in Model)
{
        <td>
            @Html.DisplayFor(modelItem => item.courseName)
            @Html.DisplayFor(modelItem => item.courseSubject)
            @Html.DisplayFor(modelItem => item.institute)
        </td>
        if (counter % 3 == 0)
    {
            @:</tr><tr> 
    }
}
       </tr>
</table>

I want to display records in a table with 3 columns per row. This is the way how I tried. But still all records in one row. How i can made it.

Upvotes: 1

Views: 1497

Answers (2)

Shyju
Shyju

Reputation: 218722

You need to update the counter variable inside the loop. That should do it.

<table>
    @{var counter = 1; }
    <tr>
        @foreach (var item in Model)
        {
            <td>
                @Html.DisplayFor(modelItem => item.courseName)
            </td>
            if(counter%3 == 0)
             {
                 @:</tr><tr>
             }
            counter++;
        }
    </tr>
</table>

Upvotes: 1

mituw16
mituw16

Reputation: 5250

If I am reading your question correctly, you want 3 columns per row?

If that's the case make the following change to your HTML structure. You need to add three <td> elements to make three columns

@foreach (var item in Model)
{
    <td>
        @Html.DisplayFor(modelItem => item.courseName)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.courseSubject)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.institute)
    </td>
    if (counter % 3 == 0)
    {
        @:</tr><tr> 
    }
}

Like Shyju suggested in his answer, I'm not really sure what you're doing with a counter there, as it's not being incremented on each iteration of the loop.

Upvotes: 0

Related Questions