William William - 1 month ago 17
Javascript Question

ASP.NET MVC / JavaScript - Decode Encoded HTML String from C# amper

I am attempting to access a static piece of HTML from JavaScript. Here is what I am doing:

In _Header.cshtml:

string HTMLContent = @Server.HtmlDecode("<div>Hello World</div>");

<script type="text/javascript">
var StaticHTML = @HTMLContent;

However, I am getting the following error:

Uncaught SyntaxError: Unexpected token &

When I step through it does appear that the HTMLContent variable is being printed in JavaScript as if it were Unencoded.

What am I missing here?


When razor executes the code in your view, @ will encode the value of your C# expression. So you want to avoid doing that. You may use Html.Raw method which does not do any html encoding.

Since you are assigning the value to the js variable, you should wrap it in quotes(single or double).

This should work.

var StaticHTML = "@Html.Raw(HTMLContent)";