Home > other >  Blazor - Change Color of text based on condition
Blazor - Change Color of text based on condition

Time:07-22

I have this five ratings:

    if (model.CIIattainedrequired2021 > model.d4)
    {
        model.CIIrating2021 = "E";
    }
    if (model.CIIattainedrequired2021 < model.d4)
    {
        model.CIIrating2021 = "D";
    }
    if (model.CIIattainedrequired2021 < model.d3)
    {
        model.CIIrating2021 = "C";
    }
    if (model.CIIattainedrequired2021 < model.d2)
    {
        model.CIIrating2021 = "B";
    }
    if (model.CIIattainedrequired2021 < model.d1)
    {
        model.CIIrating2021 = "A";
    }

I display them in tables:

    <td >
    <p>@model.CIIrating2019</p>
</td><td >
    <p>@model.CIIrating2020</p>
</td><td >
    <p>@model.CIIrating2021</p>
</td><td >
    <p>@model.CIIrating2022</p>
</td><td >
    <p>@model.CIIrating2023</p>
</td><td >
    <p>@model.CIIrating2024</p>
</td><td >
    <p>@model.CIIrating2025</p>
</td><td >
    <p>@model.CIIrating2026</p>

And depending on the answer i would like to show the text in different colors as follow:

A-GREEN B-LIGHTGREEN C-YELLOW D-ORANGE E-RED

CodePudding user response:

For the text, add this:

<p style="color:@TextColor(model.CIIrating2020);">@model.CIIrating2020</p>

Then in your code add something like this to return the correct color based on the text:

private void TextColor(string text) {
switch(text) 
{
  case "A":
    return "#00FF00"
    break;
  case "B":
    return "#90EE90"
    break;
  //etc....
}
}

CodePudding user response:

  1. First thing you will need will be to add a class using a variable in your td element.
< td  >
  1. Then in the code section of the page/component you need the variable you are using as the class above and a method that switches classes based on your logic:

    @code{

         private string Color-code{get;set;}

        -//method that identifies the color

   

     private void setColorClassMethod()
       {

          if(condition)

            {

              //Assuming you want to assign blue class in the case

              Color-Code="blueClass";

            }
       }
        
    }
  1. Finally in site.css file add colors to the classes you used above in variables like:

      .blueClass


  {

     //if you want to change background color
 
     background-color:blue;
 
     //if you want to change text color
    
  
 
     color:blue;
     
     }

You can also achieve the same results via in line css. But I suggested classes because you might need to add further styling later to the td.

  • Related