I want to render in .NET a string destined for Javascript, say:
<html>
...
<script>
alert('<%= this.MyStringHere %>');
</script>
</html>
How should I encode MyStringHere? Do I need HttpUtility.HtmlEncode(HttpUtility.JavaScriptStringEncode(unencodedString))
or is just HttpUtility.JavaScriptStringEncode(unencodedString)
sufficient? Or are both wrong?
Feel free to mention alternative server tag <% solutions in your answer too, but I'm looking for the code-based solution, the example is a little contrived.
HTMLEncode() Method is used to convert an HTML code to a string. It is used to encode form data and other client request data before using it in the web application.
The <script> tag can be placed in the <head> section of your HTML or in the <body> section, depending on when you want the JavaScript to load. Generally, JavaScript code can go inside of the document <head> section in order to keep them contained and out of the main content of your HTML document.
HTML encoding ensures that text will be correctly displayed in the browser, not interpreted by the browser as HTML. For example, if a text string contains a less than sign (<) or greater than sign (>), the browser would interpret these characters as an opening or closing bracket of an HTML tag.
JavaScriptStringEncode() Method will convert html content to javascript compatible.
You only need to encode the script for JS use, no need to double encode using HTML encoding. Just HTML encoding will not work either because it will not encode \n
etc.
<script>
alert(<%=HttpUtility.JavaScriptStringEncode(this.MyStringHere, true)%>);
alert("<%=HttpUtility.JavaScriptStringEncode(this.MyStringHere, false)%>");
</script>
Note that JavaScriptStringEncode
will not add the double quotes by default - see official docs.
If you have server-side JSON package installed, you could also use that - and it will also work for arrays, dictionaries etc.. Note that it will also add quotes for strings so you do not add them yourself.
You also have to remember that you cannot use <%: text %>
syntax since that does the HTML encoding. In MVC Razor views you even have to explicitly disable HTML encoding by using @Html.Raw(Json.Encode(...))
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With