William
William

Reputation: 3395

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;
</script>

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?

Upvotes: 0

Views: 1851

Answers (1)

Shyju
Shyju

Reputation: 218702

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)";
console.log(StaticHtml);

Upvotes: 3

Related Questions