Skip to content Skip to sidebar Skip to footer

How Can I Loop Through My Table To Display Contents Side By Side In MVC Razor View?

Hi i want help in putting contents side by side. Right now i can display content separately in left side and right side. But i need to display records from database. For this i am

Solution 1:

Instead of

@foreach (var item in Model)

use

@for (var i=0; i < Model.Count; i+=2)
{

}

and access properties of model like

 @Model[i].ID

In order to determine which should go to right which should go left you can use

@Model[i].ID for left 

and

@if(i+1 < Model.Count)
{
  Model[i+1].ID for right
}

Just make sure that i+1 is never more than Model.Count


Solution 2:

Using this pattern you can make as many columns as you like. If you're using an html table you need to also test if you need blank cells when the total collection size is not divisible by columns.

@{
    int columns = 3;
}

@for (int i = 0; i < Model.Count; i++)
{
    var currentModel = Model[i];

    int col = i % columns;

    if (col == 0)
    {
        // left
    }
    else if (col == 1)
    {
        // middle
    }
    else  // col == 2
    {
        // right
    }
}

Post a Comment for "How Can I Loop Through My Table To Display Contents Side By Side In MVC Razor View?"