Use the .NET HtmlString Class to Output Raw HTML

I posted recently about sending raw unencoded HTML to the client using the Html.Raw() method with MVC 3 and the Razor view engine. I wanted to extend a bit on that post regarding the magic underlying the Html.Raw() method, the HtmlString class in the System.Web namespace of the .NET framework class library. You can use the HtmlString class in .NET code outside of the Razor view engine to preserve HTML markup you want to send to the browser.

The HtmlString class represents an HTML-encoded string that should not be encoded again. When you create a new instance of this class using a string value, your string value will not be HTML-encoded. This allows you to output exactly the markup you want to the client without worrying about extra encoding.

For example, let’s say you want to output the following HTML to the browser without any extra encoding.

[sourcecode language=”html”]

<div id="foo" style="background-color: fuchsia">This is my <emphasis>cool</emphasis> div!</div>

[/sourcecode]

Without using the HtmlString class, if you emit this from a .NET class then it will almost always be encoded before being sent to the client. However, simply wrapping your original markup in an HtmlString preserves your beautiful (or not so beautiful!) markup on its trip to the client. Check out the following C# example as a model.

[sourcecode language=”csharp”]

var unencodedString = new System.Web.HtmlString("<div id="foo" style="background-color: fuchsia">This is my <emphasis>cool</emphasis> div!</div>");

[/sourcecode]

Note that you can also use the System.Web.Mvc.MvcHtmlString class to do the same thing if you want to stay exclusively in the MVC namespace.

Comments are closed.

Sign in
classic
Forgot password?
×
Sign up

(*) Required fields

I agree with OptimaSales Terms & Privacy Policy

×