george george - 5 months ago 25
HTML Question

razor add class if condition is false

Hey i need to add class to div only if count is higher than 6 but i dont know where is the problem. Thanks for any advice

@{
int count = 0;
}
@foreach (var item in Model.Models)
{
<div class="col-xxs-12 col-xs-6 col-sm-4 @(count < 6 ? "" : "dismiss")">
<a href="@Url.Action("Detail", "Product", new { productID = item.ProductID, parentCategoryID = item.CategoryID, isProductModel = true })" class="model-wrap">
<div class="box">
<div class="img-wrap" style="background-image: url( @Url.Content(Utils.ProductImagePath(item.ImageID)) )"></div>
<div class="arrow f16">@item.Name <i class="fa fa-angle-right theme-color" aria-hidden="true"></i></div>
</div>
</a>
</div>
} count++;
</div>

Answer

Your existing code looks fine as it will only add the dismiss class if your count value is greater than or equal to 6 via your ternary statement :

<div class="col-xxs-12 col-xs-6 col-sm-4 @(count < 6 ? "" : "dismiss")">

Have you considered using a for loop, which will automatically handle storing the current index for you? This might make keeping track of the count a bit easier and resolve any possible issues with your counter not being scoped properly

@for (var i = 0; i < Model.Models.Count(); i++)
{
    // Store a reference to your item to ease syntax
    var item = Model.Models.ElementAt(i);
    <div class="col-xxs-12 col-xs-6 col-sm-4 @(i < 6 ? "" : "dismiss")">
      <a href="@Url.Action("Detail", "Product", new { productID = item.ProductID, parentCategoryID = item.CategoryID, isProductModel = true })" class="model-wrap">
        <div class="box">
            <div class="img-wrap" style="background-image: url( @Url.Content(Utils.ProductImagePath(item.ImageID)) )"></div>
            <div class="arrow f16">@item.Name <i class="fa fa-angle-right theme-color" aria-hidden="true"></i></div>
        </div>
      </a>
  </div>
}