Wrong text encoding in string sent to javascript

2019-04-09 13:13发布

问题:

I have a javascript method which is receiving a UTF-8 encoded string (ViewBag.errorText), and uses this as a parameter to a new function.

The problem is that the text displayed in show_error_dialog is displaying the html escaped characters (æ&#248 etc') and not the intended ("æåø" etc.).

I presume the problem is the enclosed <text> tags but can't seem to get around this.

<script type="text/javascript" charset="utf-8">
    function performLoadOperations() {
        @if(ViewBag.errorText!= null) {
            <text>show_error_dialog('@ViewBag.errorText');</text>
        }
    }
</script>

回答1:

I think all Razor-inserted text is HTML-encoded by default. Use Html.Raw() to pass the string unencoded.

<script type="text/javascript" charset="utf-8">
    function performLoadOperations() {
        @if(ViewBag.errorText!= null) {
            <text>show_error_dialog('@Html.Raw(ViewBag.errorText)');</text>
        }
    }
</script>


回答2:

Use: @Html.Raw(Ajax.JavaScriptStringEncode(Model))

to safely insert values into javascript



回答3:

I'm not sure but i think there was unescape() function with js. Try to pass your text with it. It might help



回答4:

just use javascript escape function:

function encode_utf8( s )
{
  return unescape( encodeURIComponent( s ) );
}

function decode_utf8( s )
{
  return decodeURIComponent( escape( s ) );
}