JavaScriptEncoder converts text into a representation safe for insertion into JavaScript. It prevents JavaScript contexts from receiving HTML encoding, which can display characters such as quotation marks incorrectly. section 29.1
Encoding a value in Razor
Inject the encoder and call Encode() before inserting a value into a script: @inject System.Text.Encodings.Web.JavaScriptEncoder encoder; <script>var name = '@encoder.Encode(name)'</script>. A quotation mark becomes the safe Unicode sequence \u0022. section 29.1
Prefer writing values into HTML attributes and reading them with JavaScript instead of embedding values directly in scripts. This usually removes the need for JavaScriptEncoder and keeps encoding aligned with the output context. section 29.1
Listing 29.1 Passing values to JavaScript by writing them to HTML attributes
<div id="data" data-name="@name"></div>
<script> #1
var ele = document.getElementById('data'); #2
var name = ele.getAttribute('data-name'); #3
</script>
Shows the recommended attribute-based flow: place the value in data-name, retrieve the element, and read the attribute from JavaScript. section 29.1
