I'm attempting to create a 2 column bootstrap layout with dynamic data coming from an MVC model, using Razor. Goal is to have unique data in each column until looping is complete. The following code repeats the same data in both columns. What logic would I need in order to make this work

@{
int i=1;
foreach (var item in Model)
{
    <div class="row">
        <div class="col-md-6">
            <input type="checkbox" checked="@item.Checked" />
            @item.Description
        </div>
        <div class="col-md-6">
            <input type="checkbox" checked="@item.Checked" />
            @item.Description
        </div>
    </div>
    i++;
}

}

1 Answers

1
devlin carnate On Best Solutions

You need to iterate your items over each column in order to get different items in each. One way to do this is to track "even" and "odd" iterations and display items based on that.

<div class="row">
int cnt1 = 0;
foreach (var item in Model)
{
  if(cnt1 % 2 == 0) {
    <div class="col-md-6">
        <input type="checkbox" checked="@item.Checked" />
        @item.Description
    </div>
  }
  cnt1++;
}
int cnt2 = 0;
foreach (var item in Model)
{
  if(cnt2 % 2 != 0) {
    <div class="col-md-6">
        <input type="checkbox" checked="@item.Checked" />
        @item.Description
    </div>
  }
 cnt2++;
}
</div> //end row

Another way to achieve this would be to divide your items into 2 lists in the controller and iterate over list 1 for the first column and list 2 for the second column.