Search code examples
cssrazor

CSS in cshtml for MVC : Conditional formatting based on a keyword in text


I am implementing sorting for ASP.NET Core MVC, and I should like to put a background colour to the header of the column on which the sorting is based.

On other threads I saw using scripts could be a good idea, but I am not quite at ease to say what is a script and what is the page contents.

The header takes the good colour, but "}else{" appears above it, which is not quite aesthetical.

If I put @ in front of }, I fear it will not appreciate a lot.

Can anyone point me to the right syntax?

@{if(ViewData["SortOrder"].ToString().Equals("Date"))}
  <span>
}else{
  "<span style='background-color:yellow;'>"               
}

@Html.DisplayNameFor(model => model.OrderDate)
</span>

When reading again, it seems to me that my syntax should colourise the header only if it is NOT in the sort column. But in fact it is the opposite. Is it strange, or am I tired?

I have found something that runs. The question will be, is it possible to keep the script inside the table?

At the beginning of the page I put this:

@{
    ViewData["Title"] = "Index";
    string strStyle;

    string Colorize(){
        if(ViewData["SortOrder"].ToString() == "Date")
        {
            strStyle = "background-color:yellow;";
        }
        else
        {
            strStyle = "";
        }
        return "";
    }
}

And then in the table, inside the th element:

@Colorize()
@Html.Raw("<span style=\"" + strStyle + "\">")
                
@Html.DisplayNameFor(model => model.OrderDate)
</span>

For Colorize(), void type would have done the trick, but it is not accepted to insert it into the table.


Solution

  • Here I can see a mistake that
    In this case you are trying to apply background-color if the given condition is false.

    @{if(ViewData["SortOrder"].ToString().Equals("Date"))}
      <span>
    }else{
      "<span style='background-color:yellow;'>"               
    }
        
    

    And the case that is working for you is this

    if(ViewData["SortOrder"].ToString() == "Date")
    {
        strStyle = "background-color:yellow;";
    }
    else
    {
        strStyle = "";
    }
        
    

    Here I can see that you are matching the same condition but now you are trying to give background-color if condition is true.
    So as far as I think you want to apply background-color when the given condition is true.

    @if(ViewData["SortOrder"].ToString().Equals("Date"))
    {
        <span style='background-color:yellow;'>@Html.DisplayNameFor(model => 
        model.OrderDate)</span>
    }
    else
    {
        <span>@Html.DisplayNameFor(model => model.OrderDate)</span>
    }