Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrong text encoding in string sent to javascript

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>
like image 840
user204884 Avatar asked Jun 09 '11 10:06

user204884


People also ask

Are JavaScript strings UTF-8?

It helps, though, when you realize that Javascript string types will always be encoded as UTF-16, and most of the other places strings in RAM interact with sockets, files, or byte arrays, the string gets re-encoded as UTF-8.

What encoding do JavaScript strings use?

Strings in JavaScript are encoded using UTF-16.

Does JavaScript use UTF-8 or UTF-16?

Most JavaScript engines use UTF-16 encoding, so let's detail into UTF-16. UTF-16 (the long name: 16-bit Unicode Transformation Format) is a variable-length encoding: Code points from BMP are encoded using a single code unit of 16-bit. Code points from astral planes are encoded using two code units of 16-bit each.

Why does JavaScript use UTF-16?

JS does require UTF-16, because the surrogate pairs of non-BMP characters are separable in JS strings. Any JS implementation using UTF-8 would have to convert to UTF-16 for proper answers to . length and array indexing on strings. Still doesn't mean that it has to store the strings in UTF-16.


1 Answers

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>
like image 85
Zruty Avatar answered Sep 22 '22 11:09

Zruty