MVC Razor Tip: Output Raw Unencoded HTML

I’m working on an MVC Razor project and need to output some raw HTML to disable an HTML text box if the text box is populated with a value. I realized, though, that my initial attempt didn’t render quite the output I expected.

My original code to output the  disabled=”disabled” attribute (gotta love XHTML compliance!) was being HTML encoded by the Razor view engine so it looked like disabled="disabled". This is okay when you are citing HTML in an article for human readers but causes problems when you are trying to code against a form.

Original Code

[sourcecode language=”csharp”]

@(!String.IsNullOrEmpty(userName) ? "disabled="disabled"" : String.Empty)

[/sourcecode]

This rendered the following output.

[sourcecode language=”html”]

<input id="accountname" name="accountname" maxlength="120" value="UserName" disabled=&quot;disabled&quot; />

[/sourcecode]

Second Attempt

I tried to fix the issue using the Razor <text> tag to output the verbatim output (yes, I tried the Razor @: verbatim string escape sequence but it wasn’t parsable the way I had it) and ended up with the following output, which was farther away from my desired output.

[sourcecode language=”html”]

<input id="accountname" name="accountname" maxlength="120" value="UserName" &lt;text&gt;disabled=&quot;disabled&quot;&lt;/text&gt; />

[/sourcecode]

Successful Attempt

I finally found a relatively elegant method to output unescaped HTML using Razor: the Html.Raw() method. The following Razor code renders the final desired output.

[sourcecode language=”csharp”] @(!String.IsNullOrEmpty(userName) ? Html.Raw("disabled="disabled"") : Html.Raw(String.Empty))
[/sourcecode]

HTML Output

[sourcecode language=”html”] <input id="accountname" name="accountname" maxlength="120" value="UserName" disabled="disabled" />
[/sourcecode]

So just remember that if you’re trying to output unescaped HTML, use the Html.Raw() method. Phil Haack has a great C# Razor Syntax reference that helped point me in the right direction. You can refer to another nice inline Razor syntax guide for more help.

1 Comment

Sign in
classic
Forgot password?
×
Sign up

(*) Required fields

I agree with OptimaSales Terms & Privacy Policy

×