Conditional Formatting with ASP.NET MVC
I have an ASP.NET MVC application that uses Razor in views. In my opinion I have the following:
<table style="width:100%;">
...
</table>
I mean, if (items.Count == 0)
then the background color of the table should be orange. However if (items.Count > 0)
, I want the background color of the table to be gray. How can I do this with Razor?
Thank!
source to share
CSS
.table {
background-color: grey;
}
.table.empty {
background-color: orange;
}
Razor:
<table class="table @(items.Count == 0 ? "empty" : null)">
This will display as <table class="table">
or <table class="table empty">
.
In general, these are small rules of how basic values ( null
, ""
, true
, false
) are displayed inside an HTML attribute in the Razor:
Razor Rendered HTML
----------------------------------------
<abc xyz="s @(null) t"> <abcxyz="s t">
<abc xyz="@(null)"> <abc>
<abc xyz="@("")"> <abc xyz="">
<abc xyz="@(true)"> <abc xyz="xyz">
<abc xyz="@(false)"> <abc>
Note the difference between null
and ""
(empty string).
As Chris Pratt points out in his comment, if you don't need to support pre-IE 9, you can use a pseudo-class :empty
to get a similar effect without the ternary operator.
CSS
.table {
background-color: grey;
}
.table:empty {
background-color: orange;
}
Razor:
<table class="table">
source to share