Razor If/Else conditional operator syntax

asp.net Mvc-3Razor

asp.net Mvc-3 Problem Overview


Not having much luck, I have the following if/else statement in Razor which works perfectly

<small>
  @if(deletedView){
     @:Deleted
  } 
  else {
     @:Created
  } by
</small> 

I am trying to do something like this:

<small>
  @(deletedView) ? @:Deleted : @:Created by
</small>

But that fails miserably. What is the proper syntax?

asp.net Mvc-3 Solutions


Solution 1 - asp.net Mvc-3

You need to put the entire ternary expression in parenthesis. Unfortunately that means you can't use "@:", but you could do something like this:

@(deletedView ? "Deleted" : "Created by")

Razor currently supports a subset of C# expressions without using @() and unfortunately, ternary operators are not part of that set.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionB ZView Question on Stackoverflow
Solution 1 - asp.net Mvc-3Andrew Stanton-NurseView Answer on Stackoverflow