div color in razor view

2019-06-25 06:27发布

问题:

I am displaying a list of products in my asp.net MVC 3 razor view. I am displaying products in foreach loop inside div. I want that if product is on sale then div color is red. How can I change background color of div in razor view?

回答1:

Razor view:

@foreach (Product product in Model.ProductList)
{
    string saleClass = product.IsOnSale ? "onSale" : "regular";
    <div class="@saleClass">
        @product.Description
    </div>
}

Stylesheet:

onSale
{
    background-color: red;
}

regular
{
    background-color: white;
}

Or in a more direct fashion:

@foreach (Product product in Model.ProductList)
{
    string style= product.IsOnSale ? "background-color: red" : "background-color: white";
    <div style="@style">
        @product.Description
    </div>
}