Put data into variable table columns

I was working on an ASP.net MVC project and I am currently fetching data from a database and displaying it in interleaved rows. Thus, the data display will be as follows.


| 1st | 2nd |

| 3rd | Fourth |

Etc. I managed to get it right with the following code. This seems pretty inefficient to me, and I am asking if there is a much easier way to do this. Thank you.

@{
@:<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>

}

      

+3


source to share


1 answer


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

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 it probably won't compile, but it should get you going.

+3


source







All Articles