I am implementing sorting for ASP.Net MVC Core, 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.
2
Answers
Nobody proposed a way to keep the script inside the table. So, for the moment being, I am going to assume I chose the good path. A few rules have to be respected when using @{} in a cshtml file:
That way, if you have strange messages of the compiler after adding two or three lines with @{}, you can delete them and the project compiles again.
I now have two colours, one for ascending sorting, and one for descending sorting. Each sorting is obtained with a different value of SortOrder in the URL.
Two fields can be sorted, and for each, one value of SortOrder gives ascending sorting, another one gives descending sorting.
Thus, my function accepts two arguments, one for the value of SortOrder that gives ascending sorting, one for the value that gives descending sorting.
Each field header appears on yellow background if it is sorted ascending, on orange background if it is sorted descending, on white background if it is not the sorting key.
Lower in the page I have this:
That seems to work OK. If someone has a more simple solution it can be interesting.
Here I can see a mistake that
In this case you are trying to apply background-color if the given condition is false.
And the case that is working for you is this
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.