noclist
noclist

Reputation: 1819

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

}

Upvotes: 3

Views: 4048

Answers (2)

Shaahin
Shaahin

Reputation: 1225

With respect to delvin carnate solution, you can even do it in a single foreach loop. It would be faster, because you iterating only once the loop.

  <div class="row">
        @{int a = 0; }
        @foreach (var auhtor in authors)
        {
            if (a % 2 == 0)
            {
            <div class="col-sm-6">
                @Html.ActionLink(auhtor, "Author", new { id = auhtor }, new { @class = "btn text-primary" })
            </div>
            }
            else
            {
            <div class="col-sm-6">
                @Html.ActionLink(auhtor, "Author", new { id = auhtor }, new { @class = "btn text-primary" })
            </div>
            }
            a++;
        }
    </div>

Upvotes: 2

devlin carnate
devlin carnate

Reputation: 8602

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.

Upvotes: 4

Related Questions