8

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>

4 Answers 4

19

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>
Sign up to request clarification or add additional context in comments.

2 Comments

This opens you up to an XSS exploit, you need to re-encode errorText for insertion into javascript.
Couldn't understand can you please explan Mr.Fox
5

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

to safely insert values into javascript

1 Comment

Can you explain a bit about this, why this is safely and what does exactly each function? Thanks a lot, this worked for me !!!
1

just use javascript escape function:

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

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.