Conditional but static text in ASP.net Razor Pages

On a recent work project I wanted to display some static text on an ASP.net Razor Page, but only if a certain field in the database was empty or whitespace. So, if the entity’s title wasn’t set in the database, display a generic title in the web front-end.

I tried using a normal if … else block but had trouble with it because the text was supposed to be inside all inside of the HTML title element and Razor Pages was getting confused (as was I) when I tried to include static text inside the if block and  C# code inside the else block.

I first tried:

But of course you can’t really have plain strings inside the if block like that.

Luckily a colleague heard what I was trying to do and send me a reference to a blog or Stack Overflow question describing how to do it. The solution required using the ternary operator with an IsNullOrWhiteSpace  test to display the static text string literal if true , and the actual title inside an interpolated string if false .

Previously in my development experience I’d seen the ternary operator around, but never really understood what it was for or how it works. It’s surprisingly simple: after any conditional test, place a “?” (question mark sign) followed by the operation if that condition is true, then a colon, then the operation if it’s false. 

Another common use for the ternary operator is to assign values to variables in one line. Here, the syntax is: variable = condition ? value if true : value if false

So, 

is equivalent to:

Interestingly, while the ternary operator works like a shorthand if statement, it’s actually an operator, not a statement. So the following is invalid:

The full source code to my above snippets that I used for testing them is below.

This post has unexpectedly become an introduction to the ternary operator (or conditional operator) as well as a demonstration of how I solved the problem of static test  conditional upon a value inside a Razor page.  But I think it’s still useful to understand how it works and have the option even if you don’t need it often (and an if then else block is easier to scan through) – it’s likely there are other methods of achieving this, but pre-computing it would have been even more verbose.

Posted by Anthony