Html literal in Razor ternary expression

Viewed 18920

I'm trying to do something like the following

<div id="test">
    @(
        string.IsNullOrEmpty(myString)
          ? @:&nbsp;
          : myString   
    )
</div>

The above syntax is invalid, I've tried a bunch of different things but can't get it working.

4 Answers

Another updated approach thanks to new features is to create a helper function right in the view. This has the advantage of making the syntax a little cleaner especially if you are going to be calling it more than once. This is also safe from cross site scripting attacks without the need to call @Html.Encode() since it doesn't rely on @Html.Raw().

Just put the following right into your view at the very top:

@helper NbspIfEmpty(string value) {
  if (string.IsNullOrEmpty(value)) {
    @:&nbsp;
  } else {
    @value
  }
}

Then you can use the function like this:

<div id="test">
    @NbspIfEmpty(myString)
</div>
Related