0

I've noted that @ statement in Razor templates converts quotes in strings into HTML symbols.

How can I show correct HTML attribute then? Sample code:

<body@(ViewBag.Highlight == true ? " onload=\"prettyPrint()\"" : "")>

result:

 <body onload=&quot;prettyPrint()&quot;>

That's completely incorrect. How can i achieve normal:

 <body onload="prettyPrint()">

in my case?

I've tried HtmlString object from this answer. But it's impossible to convert HtmlString to string even with explicit type cast.

Community
  • 1
  • 1
shytikov
  • 9,155
  • 8
  • 56
  • 103

1 Answers1

2

You will need to use Html.Raw(). Try it this way:

@Html.Raw(String.Format("<body{0}>", ViewBag.Highlight == true ? " onload=\"prettyPrint()\"" : ""))

As the documentation says:

Returns markup that is not HTML encoded.

shytikov
  • 9,155
  • 8
  • 56
  • 103
Michal Klouda
  • 14,263
  • 7
  • 53
  • 77
  • This way it works, thank you! One small correction: have to use `ViewBag.Highlight == true`, otherwise I get an error `Cannot convert null to 'bool' because it is a non-nullable value type`. – shytikov Oct 24 '12 at 16:01