Search code examples
razorbootstrap-4

How to alternate a row color for a Bootstrap grid system


I have a loop on my MODEL in the view and I simply want to make every alternate Div ROW a different color. Is there a way I can check if my variable i Modulus by 2 ==0 and then set the backcolor, or is there even a better way

                        @for (var i = 0; i < Model.Transactions.Count; i++)
                        {
                            <div class="row">
                                <div class="col">
                                    <label asp-for="@Model.Transactions[i].TransactionId" />@Model.Transactions[i].TransactionId
                                </div>

Solution

  • Your own answer uses the right modulus operator to check for an even/odd index value.

    I don't know if this the best way to do it but below is how I overcome my issue

    Adding a class name instead enables more style flexibility. (The snippet below assumes you have a section called Styles in your _Layout.cshtml.)

    @section Styles {
        <style>
            .odd-row {
                background-color: #f1f1f1;
            }
    
            .even-row {
                background-color: #e1e1e1;
            }
        </style>
    }
    
    @for (int i = 0; i < Model.Transactions.Count; i++)
    {
        string altClassName = i % 2 == 0 ? "even-row" : "odd-row";
        <div class="row @altClassName">
            <div class="col">
                <label asp-for="@Model.Transactions[i].TransactionId">@Model.Transactions[i].TransactionId</label>
            </div>
        </div>
    }