26

I want to write something like:

@( checkCondition ? "<span class='label'>Right!</span>" : "")

But it is showing the source code instead the HTML, there is a easy way to do this?

Thank you!

Liam
  • 27,717
  • 28
  • 128
  • 190
Santiago
  • 2,190
  • 10
  • 30
  • 59
  • 1
    http://stackoverflow.com/questions/4091831/how-to-use-ternary-operator-in-razor-specifically-on-html-attributes – billyonecan May 08 '13 at 14:30

3 Answers3

61

You can use @Html.Raw(mystring) method like this:

@( checkCondition ? Html.Raw("<span class='label'>Right!</span>") : Html.Raw(""))
Volodymyr Machula
  • 1,564
  • 1
  • 15
  • 20
26

You can be even more concise (granted harder to read) with this:

@Html.Raw(checkCondition ? "<span class='label'>Right!</span>": string.Empty)
Mish Ochu
  • 456
  • 4
  • 6
2

We can also do like that:

@if (checkCondition ) { <text><span class='label'>Right!</span></text> }

The text tag allows you to write html with syntax highlighting!

A. Morel
  • 9,210
  • 4
  • 56
  • 45