Is there a standard way to encode a .NET string into JavaScript string for use in MS Ajax? Is there a standard way to encode a .NET string into JavaScript string for use in MS Ajax? asp.net asp.net

Is there a standard way to encode a .NET string into JavaScript string for use in MS Ajax?


A probem with this function is that it doesn't encode characters that are typically out-of-band in encapsulating HTML... so you'd have trouble if you tried to include a string with " inside an attribute value, or if you had a string with the sequence </script> inside a script element. That could lead to script-injection and XSS.

You could add:

            case '<':                sb.Append("\\x3C");                break;            case '"':                sb.Append("\\x22");                break;            case '&':                sb.Append("\\x26");                break;

In general it would probably be better to use a standard JSON encoder than brew your own JS string literal encoder. This will allow you to pass any simple datatype to JS rather than just strings.

In .NET 3.5 you get JavaScriptSerializer, however note that whilst this does encode < to \u003C (so the output will be suitable for use in a <script> element), it doesn't encode & or ", so HTML-escaping would be needed to include such content in an attribute value and a CDATA wrapper would be needed for XHTML script elements.

(In common with many JSON encoders, it also fails to encode the U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR characters. The above code does, due to escaping all non-ASCII characters. This causes ‘unterminated string literal’ errors when these characters are included in a JS string literal, because JavaScript unhelpfully treats them the same as an ASCII newline.)


This is an old thread, but you may be interested to know about the Microsoft AntiXSS library which has a Javascript encode method which works for .Net 2 onwards.

http://msdn.microsoft.com/en-gb/security/aa973814.aspx