3

What I'm trying to do is simple:

<td class="bold-and-caps">@{if (++i == 1) { subsec.Title } else { String.Empty } } </td>

except I'm getting

"Only assignment, call, increment, decrement, await and new object expressions can be used as a statement"

on subsec.Title and String.Empty.

How am I supposed to write "If condition, output X" type statements in Razor?

user5648283
  • 5,913
  • 4
  • 22
  • 32
  • Correct syntax of `@if` is shown in linked [duplicate](http://stackoverflow.com/questions/4607843/razor-if-else-conditional-operator-syntax) as well as alternative conditional operator syntax. – Alexei Levenkov Feb 05 '16 at 17:16

2 Answers2

10

You can use ternary operator for it like:

<td class="bold-and-caps">@( (++i == 1) ? subsec.Title : String.Empty)</td>
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
3

You can do this by code like this:

<td class="bold-and-caps">
    @if (++i == 1)
        { @subsec.Title }
    else
        { <text>@string.Empty</text> }
</td>

But in your case you don't have to use else with empty string when you want only display something if...

<td class="bold-and-caps">@if(++i == 1){ @subsec.Title }<td>
Sousuke
  • 1,203
  • 1
  • 15
  • 25