99

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?

B Z
  • 9,363
  • 16
  • 67
  • 91

1 Answers1

187

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.

Andrew Stanton-Nurse
  • 6,274
  • 1
  • 28
  • 20
  • 1
    @David Lively already answered by thanks :) At least can "close" the question now... – B Z Jan 05 '11 at 20:12
  • 4
    +1 for 'Razor currently supports a subset of C# expressions without using @()' was wondering why @if (condition) { was giving me an error – Tom Jun 03 '11 at 13:32
  • 1
    @Andrew Nurse, As per you have mentioned, "Razor currently supports a subset of C# expressions without using @() and unfortunately, ternary operators are not part of that set". I would like to know what all operators are part of that set? Thanks! – Vikram May 29 '14 at 15:54
  • 1
    check [this](http://stackoverflow.com/a/30151780/2218697) for else if in razor – Shaiju T May 10 '15 at 13:12