Suppose you want to concat together a bunch of strings and markup, maybe like this:
var stringWithMarkup = "a" + "<br/>" + "b" + "<br/>" + "c" ;
(Let's assume you're doing something a bit more sophisticated than this, like including some variables, but bear with me for the duration here.)
And let's say your goal is to render something like this:
a
b
c
So you do this in a Razor page:
<div>
@stringWithMarkup
</div>
Guess what you get -- ? Yes, this:
a <br/> b <br/> c <br/>
This is, as they say, by design. When Razor renders strings, it automatically HTML encodes them, which is a security measure. What you might intend as HTML elements inside the string — e.g., <br/>
— are encoded in such a way that they're treated as text, not HTML (e.g. <br/>
). (This is noted a couple of times in the ASP.NET Razor ebook -- for example, see "HTML Encoding" in Chapter 2 - Introduction to ASP.NET Web Programming Using the Razor Syntax.)
However, you won't find in that chapter any info on what to do if you do want the embedded markup rendered as markup and not encoded. [Important Warning] You can do this, but it's not obvious how. I asked around, and the ever-helpful Erik Porter came to the rescue. Here's the solution in a nutshell:
<div>
@(new HtmlString(stringWithMarkup))
</div>
In other words, pass your string to a new instance of the HtmlString class. Knowing this, you can read an explanation in Scott Guthrie's blog; here's the salient bit:ASP.NET 4 introduces a new IHtmlString interface (along with a concrete implementation: HtmlString) that you can implement on types to indicate that its value is already properly encoded (or otherwise examined) for displaying as HTML, and that therefore the value should not be HTML-encoded again. The <%: %> code-nugget syntax checks for the presence of the IHtmlString interface and will not HTML encode the output of the code expression if its value implements this interface.
Scott Hunter, who's another of the ASP.NET Razor PMs, noted that this would be a good candidate for a simple helper. He suggested that you could create a helper like this:
@helper RawText(string s) {
@(new HtmlString(s))
}
Create a blank file named CustomHelpers
in the App_Code folder of the website and then copy the RawText
helper code in, save the file, done. Then you can do something like this your other pages:
<div>
@CustomHelpers.RawText(stringWithMarkup)
</div>
Slick, eh? Obviously, you can name the file and the helper anything you want, just change the syntax accordingly where you want to invoke the helper.