5

Dynamically applying style to a list item

 2 years ago
source link: https://www.codesd.com/item/dynamically-applying-style-to-a-list-item.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Dynamically applying style to a list item

advertisements

I have got a list and I want to apply a different style to each item depending on it's Id. Below is my attempt to do that but unfortunately something is wrong. Any help will be very appreciated.

@foreach (var item in Model)
{
    @if (@item.Id==0)
    {
        var css = "background-color:Aqua";
    }
    else if (@item.Id==1)
    {
        var css = "background-color:Red";
    }
    else
    {
        var css = "background-color:Green";
    }

    <div style="@css" class="box">
        @item.Info
    </div>
    <div>
        @item.Name
    </div>
}


Your if condition is already in a code block(foreach code..). So no need of @ . Also define the css varibale outside of your if-else blocks

@foreach (var item in Model)
{
    var css="background-color:Green";
    @if (@item.Id==0)
    {
        css = "background-color:Aqua";
    }
    else if (@item.Id==1)
    {
        css = "background-color:Red";
    }
    <div style="@css" class="box"> @item.Info </div>
    <div> @item.Name </div>
}

Another solution is creating a css class name string inside your loop using your item.Id or item.Code(if that exists) and using that in your markup. With this approach, you may completely eliminate the if condition checking in your razor code, thus making this a much cleaner solution than the previous one.

@foreach (var item in Model)
{
    <div class="box [email protected]">
        @item.Name
    </div>
   <div> @item.Name </div>
}

And in your css class add the css classes as needed

.myClass-0
{
  background-color:aqua;
}
.myClass-1
{
  background-color:red;
}
.myClass-2
{
  background-color:green;
}

Id's might change, so i recommend using some other properties like Code/Name etc.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK