Display records in table with fixed number of colu

2019-08-10 15:48发布

<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.

2条回答
甜甜的少女心
2楼-- · 2019-08-10 16:24

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>
查看更多
Evening l夕情丶
3楼-- · 2019-08-10 16:37

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.

查看更多
登录 后发表回答