Trying to write HTML using a Modulus conditional using Razor Core6

Solution 1:

Try this...

<code>
    @if (Model != null)
    {
        var currentCard = 0;
        foreach (var item in Model.Products)
        {
            currentCard++;
            if (currentCard % 3 == 1)
            {
                @:<div class="row">
            }
            <div class="col-lg-4">
                <div class="card">
                    @*
                    <div class="card-header">
                        <img class="card-img-top" src="~/SiteImages/MenuHome.png" style="width:128px" />
                    </div>
                    *@
                    <div class="card-body">
                        <div class="card-title">
                            @item.MenuItemName
                            <hr />
                        </div>
                        <p class="card-text>">
                            @item.MenuItemDesc - @string.Format("{0:0.00}", item.MenuItemPrice)
                        </p>
                        <button class="btn btn-primary" id="fpPlatter">View</button>
                    </div>
                </div>
            </div>
            if (currentCard % 3 == 0 || currentCard == Model.Products.Count)
            {
                @:</div>
            }
        }
    }
</code>

You will need to change Model.Products to your required Model... it was just me playing around.

Solution 2:

You are not handling all the items with the current logic. For example on the first iteration the opening div is created, but the item is not written. The html you have in the else probably needs to be done unconditionally and the rest of the optional html needs to be handled the body of the foreach loop in relation to the item html so that it lands in the proper place.

Solution 3:

There is an issue with your conditional logic. However, rather than correct it, you could just abandon it and use Bootstrap's grid system to layout your rows for you.

  • outside of your foreach loop, open a row div

  • inside your loop, output a card contained inside a div sized using the grid system

    <div class="col-md-4"> <div class="card"> ... </div> </div>

  • after exiting your loop, close the row div

This is the method recommended in Bootstrap's own documentation. It is simpler to implement and also requires less work server-side to generate your HTML.