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!

+3


source to share


3 answers


To give another option, you can set the color on the page.

@{
    var color = items.Any() ? "#CCC" : "#FF0";
}

      



And behind your tag

<table style="color:@color"></table>

      

+3


source


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">

      

+4


source


you can use ternary operator:

<table style='width:100%; @(items.Count > 0 ? "background-color: grey;" : "background-color: orange;" )'>
 ...
</table>

      

0


source







All Articles