juFo
juFo

Reputation: 18577

Overview of items in Bootstrap with asp.net mvc Razor

I'm using bootstrap and showing a grid of items. I show 6 items a row.

Currently I'm having this code below, the code works but the smell of code is bad.

@{ int rowcnt = 0; }
@for (int i = 0; i < Model.Count; i++)
{  
    if (rowcnt % 6 == 0)
    {
        @Html.Raw("<div class=\"row\">")
    }

    <div class="col-md-2 col-xs-6 col-sm-6">
        <div class="myItemContainer">
            <!-- fancy item stuff -->
        </div>
  </div>
    rowcnt++;
    if (rowcnt % 6 == 0)
    {
        @Html.Raw("</div>")
    }
}
@*for-loop end*@
@if (rowcnt % 6 != 0)
{
    @Html.Raw("</div>")
}

Is there a better way to do this with bootstrap without having to count the rows to insert div's?

I tested to just create col- elements but that creates strange rows with only a single item sometimes in a row.

item item item item
item
item item item item
item
item item item item
item
...

Upvotes: 0

Views: 815

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239400

If you actually want each set of six contained within a specific row, then no, there's no better way than what you have. However, it's not necessary to actually have separate rows. For example, it's perfectly valid to have something like:

<div class="row">
    <div class="col-md-2 col-xs-6 col-sm-6">Item 1</div>
    <div class="col-md-2 col-xs-6 col-sm-6">Item 2</div>
    <div class="col-md-2 col-xs-6 col-sm-6">Item 3</div>
    <div class="col-md-2 col-xs-6 col-sm-6">Item 4</div>
    <div class="col-md-2 col-xs-6 col-sm-6">Item 5</div>
    <div class="col-md-2 col-xs-6 col-sm-6">Item 6</div>
    <div class="col-md-2 col-xs-6 col-sm-6">Item 7</div>
    <div class="col-md-2 col-xs-6 col-sm-6">Item 8</div>
    <div class="col-md-2 col-xs-6 col-sm-6">Item 9</div>
    <div class="col-md-2 col-xs-6 col-sm-6">Item 10</div>
    <div class="col-md-2 col-xs-6 col-sm-6">Item 11</div>
    <div class="col-md-2 col-xs-6 col-sm-6">Item 12</div>
    <!-- etc -->
</div>

Each column div will take up the space it's supposed to and if it can't fit, it will simply wrap to the next line and start over. The only thing you may need to do additionally is add some custom bottom margins to the column divs, since the bottom margin that separates individual rows would no longer be there, obviously.

Technically, you were already doing this anyways, in smaller screen sizes. There, only two items would fit in a "row", but you still had six total items in each row div. As a result, the remaining 4 items were already wrapping to two additional lines on smaller screens within the same row div.

Upvotes: 0

Related Questions