将数据放入交替的表列中

时间:2021-12-07 07:59:18

I've been working on an ASP.net MVC project and currently I am pulling data from a database and displaying them in alternating rows. So the display of data will be as follows.

我一直在研究ASP.net MVC项目,目前我从数据库中提取数据并以交替的行显示它们。因此数据的显示如下。


| 1st | 2nd |

| 3rd | 4th |

And so on. I have managed to do this correctly with the following code. To me this seems pretty inefficient and I am asking is if there is a much simpler way to do this. Thanks.

等等。我已设法使用以下代码正确执行此操作。对我来说,这似乎效率很低,我想问的是,是否有更简单的方法来做到这一点。谢谢。

@{
@:<table>

int modcheck = 0;

foreach (var item in @Model)
{
    if(modcheck % 2 == 0 )
    {
        @:<tr><td style="width:400px">
        <h3>@item.Name</h3>
        @:</td>
    }

    else
    {

        @:<td style="width:400px">
        <h3>@item.Name</h3>
        @:</td></tr>
    }

    modcheck++;
}

@:</table>

}

1 个解决方案

#1


Instead of doing a foreach loop you could do a for loop and increment by two, something like:

你可以做一个for循环并增加两个,而不是做一个foreach循环,比如:

for (int x=0; x < @Model.Lenght; x += 2)
{
    @:<tr>
    @:<td style="width: 400px"><h3>@Model[x]</h3></td>
    @:<td style="width: 400px"><h3>@Model[x+1]</h3></td>
    @:</tr>
} 

My ASP is a little rusty and this probably wont compile, but it should get you going.

我的ASP有点生疏,这可能不会编译,但它应该让你去。

#1


Instead of doing a foreach loop you could do a for loop and increment by two, something like:

你可以做一个for循环并增加两个,而不是做一个foreach循环,比如:

for (int x=0; x < @Model.Lenght; x += 2)
{
    @:<tr>
    @:<td style="width: 400px"><h3>@Model[x]</h3></td>
    @:<td style="width: 400px"><h3>@Model[x+1]</h3></td>
    @:</tr>
} 

My ASP is a little rusty and this probably wont compile, but it should get you going.

我的ASP有点生疏,这可能不会编译,但它应该让你去。