razor add class if condition is false
12,933
Solution 1
Your problem here is "count++" is not in foreach loop. If you want to use foreach loop you should move "count++" inside loop.
@{
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++;
}
Solution 2
Regarding Setting Your Class
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")">
Scoping Your Iteration
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 (as count++
is outside of your foreach
loop):
@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>
}
Author by
george
Updated on June 08, 2022Comments
-
george almost 2 years
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>