Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2 column layout looping through MVC model c#

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++;
}

}

like image 657
noclist Avatar asked May 28 '26 07:05

noclist


1 Answers

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.

like image 181
devlin carnate Avatar answered May 30 '26 20:05

devlin carnate



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!