1

There is a best way to write this piece of code? (without validade if element at index i is not null)

I want to load 3 bootstrap cards with data per row and put it in 3 columns

Example and code:

 1. CARD 1 CARD 2 CARD 3
 2. CARD 4 CARD 5 CARD 6

@for (int i = 0; i < Model.Count()-1; i+=3)
{
    <div class="row top30">
        <div class="col-md-4">
            @Html.Partial("~/Views/Product/Card.cshtml", Model.ElementAtOrDefault(i))
        </div>
        @if (Model.ElementAtOrDefault(i + 1) != null) 
        {
        <div class="col-md-4">
            @Html.Partial("~/Views/Product/Card.cshtml", Model.ElementAtOrDefault(i + 1))
        </div>
        }
        @if (Model.ElementAtOrDefault(i + 2) != null)
        {
        <div class="col-md-4">
            @Html.Partial("~/Views/Product/Card.cshtml", Model.ElementAtOrDefault(i + 2))
        </div>
        }
    </div>
}

2 Answers 2

2

This one is shorter

@for (int i = 0; i < Model.Count()-1; i+=3)
{
    <div class="row top30">
        @for (int j = 0; j < 3; j++)
        {
            @if (j == 0 || (Model.ElementAtOrDefault(i + j) != null))
            {
                <div class="col-md-4">
                    @Html.Partial("~/Views/Product/Card.cshtml", Model.ElementAtOrDefault(i + j))
                </div>
            }
        }
    </div>
}
Sign up to request clarification or add additional context in comments.

Comments

0

You could loop through all the cards, and just insert a new row when it's the third card already:

<div class="row top30">
    @for (int i = 0; i < Model.Count()-1; i++)
    {
        @if (Model.ElementAtOrDefault(i) != null)
        {
            <div class="col-md-4">
                @Html.Partial("~/Views/Product/Card.cshtml", Model.ElementAtOrDefault(i))
            </div>
        }
        @if (i == 2)
        {
            </div>
            <div class="row top30">
        }
    }
</div>

}

1 Comment

Thanks for your solution.

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.