Many times we have areas of an MVC Razor view that displays based upon some condition. For example, we may want show a placeholder message if we have a blank string. In this example, we use the C# ternary/conditional operator to test the message length and display a placeholder message if the original message has a length of zero.[sourcecode language=”html”]<div id="someMessage">@(ViewBag.SomeMessage.Length > 0 ? ViewBag.SomeMessage : "No message to display")</div>[/sourcecode]
The key to this operation in Razor is to encapsulate the ternary/conditional operation, which is essentially a compound expression, in parentheses after the @ delimiter. In fact, you can pretty much encapsulate any compound expression in Razor using parentheses after the @ delimiter. This powerful feature allows for clean concise code in Razor views while providing powerful processing right inline in the view.