14

I use ASP.NET MVC and bootstrap. I have many objects (>2) in collection and for each need a <div class="col-xs-6"> but with only 2 cols in a row. How to achive this using loop? There is 1 way but I am looking for something better:

@model List<Object>
@using (Html.BeginForm("ActionName", "ControllerName"))
{
    <div class="row">
    @for (int i = 0; i < Model.Count; i++)
    {
        if (i % 2 != 0) {
        <div class="row">
            <div class="col-xs-6">
                @Html.TextBoxFor(o => o[i].Value)
            </div>
        </div>
        } else {
            <div class="col-xs-6">
            @Html.TextBoxFor(o => o[i].Value)
            </div>
        }
    }
    </div>
}

2 Answers 2

18

Close the row div and start a new one inside the loop on every 2nd iteration

<div class="row">
    @for (int i = 0; i < Model.Count; i++)
    {
        if (i > 0 && i % 2 == 0)
        {
            @:</div><div class="row"> // close and start new row
        }
        <div class="col-xs-6">
            @Html.TextBoxFor(o => o[i].Value)
        </div>
    }
</div>
Sign up to request clarification or add additional context in comments.

3 Comments

It's just amazing! Never knew this construction!
This is indeed amazing and the display works fine, but the output HTML doesn't have the first two wrapped in a row DIV. It's only every subsequent row.
@WillStrohl, Yes it does (not sure what you have done differently)
1

Using a combination of the split method found here (which I turned into a helper method)

https://www.jerriepelser.com/blog/approaches-when-rendering-list-using-bootstrap-grid-system/

and a for loop I managed to achieve the grid with indexed items

public static class SplitListHelper
{        
    public static IEnumerable<IEnumerable<T>> Split<T>(this T[] array, int size)
    {
        for (var i = 0; i < (float)array.Length / size; i++)
        {
            yield return array.Skip(i * size).Take(size);
        }
    }
}


@if (Model != null)
{
    int rowCount = 0;
    foreach (var row in Model.ToArray().Split(4))
    {
        <div class="row">
            @for (int i = 0; i < row.Count(); i++)
            {
                <div class="col-xs-3">
                    @Html.DisplayFor(m => Model[rowCount + i].Name)
                    @Html.CheckBoxFor(m => Model[rowCount + i].Selected)                    
                </div>
            }
        </div>
        rowCount += 4;
    }                       
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.