Display records in table with fixed number of colu

2019-08-10 16:31发布

问题:

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

回答1:

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>


回答2:

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.