user204884
user204884

Reputation: 1795

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>

Upvotes: 8

Views: 11979

Answers (4)

Lucent Fox
Lucent Fox

Reputation: 1795

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

to safely insert values into javascript

Upvotes: 5

melaos
melaos

Reputation: 8408

just use javascript escape function:

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

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

Upvotes: 1

Dimitar Marinov
Dimitar Marinov

Reputation: 942

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

Upvotes: 0

Zruty
Zruty

Reputation: 8667

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>

Upvotes: 19

Related Questions