简体   繁体   中英

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM