Contact   •   Products   •   Search

Rick Strahl's Web Log

Wind, waves, code and everything in between...
ASP.NET • C# • HTML5 • JavaScript • AngularJs

Embedding JavaScript Strings from an ASP.NET Page


I'm looking at a piece of code that's a custom control that embeds a bit of JavaScript into a page. Part of this JavaScript is generating some static string text directly into the page. I've been running this code for a while now as part of an application I'm working on with a customer.

But a couple of days ago I ran into a couple of problems with this control and as it turns out the problem is that the JavaScript strings embedded into the HTML stream aren't properly encoded. The code used is something like this (grossly simplified):

string markup = "Some Text";

string script = @"
embedHtml("{0}");
function embedHtml(result)
{{
    alert(result)
}}";

this.Page.ClientScript.RegisterStartupScript(typeof(Page), "embedHtml", 
            string.Format(script,markup), true);

The idea is that the code gets some text that comes from the server side and gets embedded into the page. The client script basically takes the embedded string and displays it when the page loads (the real thing embeds a bunch of HTML into the page in dynamic positions but same idea).

Can you spot the problem???

Actually this is all fine and dandy with the code above. It works fine.

But it starts becoming a problem if the text that you are embedding contains special characters. Say the string that you embed contains carriage returns, extended characters or maybe more pertinently - double quotes (which is what blew my code up originally not surprisingly since the embedded string contained HTML).

For example take this C# string assignment on the server:

string markup = "Hello \"Rick\"\r\nRock On";

which when generated into the client side with the code above results in:

embedHtml("Hello "Rick"
Rock On");

which clearly is going to cause a JavaScript  error when the page loads.

The problem is that using

embedHtml("{0}");

or

embedHtml('{0}');

is a string literal and it has to be embedded into the page properly or else code will blow up sporadically as certain characters are part of the strings embedded.

The fix for this is to encode the string to embed. The easiest way to use proper JavaScript string encoding is to use JSON encoding on  the string and you can do that with the following code:

/// <summary>
/// Encodes a string to be represented as a string literal. The format
/// is essentially a JSON string.
/// 
/// The string returned includes outer quotes 
/// Example Output: "Hello \"Rick\"!\r\nRock on"
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static string EncodeJsString(string s)
{
    StringBuilder sb = new StringBuilder();
    sb.Append("\"");
    foreach (char c in s)
    {
        switch (c)
        {
            case '\"':
                sb.Append("\\\"");
                break;
            case '\\':
                sb.Append("\\\\");
                break;
            case '\b':
                sb.Append("\\b");
                break;
            case '\f':
                sb.Append("\\f");
                break;
            case '\n':
                sb.Append("\\n");
                break;
            case '\r':
                sb.Append("\\r");
                break;
            case '\t':
                sb.Append("\\t");
                break;
            default:
                int i = (int)c;
                if (i < 32 || i > 127)
                {
                    sb.AppendFormat("\\u{0:X04}", i);
                }
                else
                {
                    sb.Append(c);
                }
                break;
        }
    }
    sb.Append("\"");

    return sb.ToString();
}

 

So now we can change the code to:

string markup = wwWebUtils.EncodeJsString("Hello \"Rick\"\r\nRock On");

string script = @"
embedHtml({0});
function embedHtml(result)
{{
    alert(result)
}}";

this.Page.ClientScript.RegisterStartupScript(typeof(Page), "embedHtml", 
            string.Format(script,markup), true);

And voila - that works correctly. The embedded string in the JavaScript now looks like this:

"Hello \"Rick\"\r\nRock On"

Note that the embedHtml({0}) code has removed the quotes around the format/replace parameter as EncodeJsString will create the string with quotes around it so there's no ambiguity about which string delimiters to use. This can also reduce the complexity of code that requires nested string expressions.

This same logic applies if you use script expressions inside of a page:

alert( <%= wwWebUtils.EncodeJsString("My name is Sam\r\nRoll on") %> );

One place where I've actually used this a lot in the past is for client script localization. If you do something like this for example:

alert( <%= HttpContext.GetGlobalResourceObject("Resources","WarrantyDetail") %> );

you can run into the same encoding problems and this code should be changed to:

alert( <%= wwWebUtils.EncodeJsString(HttpContext.GetGlobalResourceObject("Resources","WarrantyDetail")) %> );

I know a lot of people truly disdain 'legacy' ASP classic script tags, but in some cases - localization especially - they are the easiest and most readable way to accomplish the task. Of course the same rules could be implied with a Label or Literal control and encoding the text explicitly in code.

I've run into this problem on a few occasions myself and I see it frequently in other people's code. While it may not be all that common to embed string literals into JavaScript when you do need to do it  it's very important to encode the string.

It's these little details that are easy to miss when working with JavaScript so I'd thought I pass this one along... Hope this helps somebody out.

Make Donation
Posted in AJAX  ASP.NET  JavaScript  


Feedback for this Post

 
# re: Embedding JavaScript Strings from an ASP.NET Page
by Josh Stodola July 16, 2007 @ 7:02am
Interesting. Was it at all possible to utilize the Javascript escape() function?
# re: Embedding JavaScript Strings from an ASP.NET Page
by Arnold Smith July 16, 2007 @ 7:44am
Thanks, Rick. As usual you present a solid solution for a coding issue. -Arnold
# re: Embedding JavaScript Strings from an ASP.NET Page
by Rick Strahl July 16, 2007 @ 9:22am
Josh - escape() won't work if you have a string literal to deal with in the first place. Somehow a string needs to get into the document first. What we'd need is a C# escape() function <s>
# re: Embedding JavaScript Strings from an ASP.NET Page
by Steven Smith July 16, 2007 @ 11:36am
Rick,
I'm working on something similar, but want to add something for you. There are many HTML entities that will not render correctly in other browsers. For instance right double quote, left double quote, trademarks, etc. can all cause problems depending on the user's encoding settings. It's best to translate these from a literal TM character to the &trade; entity. I have a function that parses a string and does such replacements - it would be easy to add to your switch() statement above.

Steve
# re: Embedding JavaScript Strings from an ASP.NET Page
by Rick Strahl July 16, 2007 @ 12:15pm
Steve - you're doing this for HTML Encoding then? That's a bit different I think.

Hmmm... I thought that JavaScript always uses UTF-8 formatting for strings, but then maybe that's just because I always force everything into UTF-8. Seems to be using anything but UTF-8 for page encoding would be a bad idea especially since ASP.NET makes that so easy from designer all the way through the Response Encoding.
# re: Embedding JavaScript Strings from an ASP.NET Page
by Steven Smith July 16, 2007 @ 1:00pm
In my case these are for text-based ads that may be displayed on any web site, running on any server (and often in other languages). So I can't count on the page using any particular encoding.
# re: Embedding JavaScript Strings from an ASP.NET Page
by Speednet July 17, 2007 @ 6:18pm
Great utility function Rick, thanks very much for sharing it!
# Localizing text inside <div> or any regular inner text - ASP.NET Forums
by ASP.NET Forums July 18, 2007 @ 11:05am
# re: Embedding JavaScript Strings from an ASP.NET Page
by Andrei Vleju August 22, 2007 @ 3:30am
How about if the string contains an apostrophe? I don't see it treated in the switch there, so my guess is that it will crash..
# re: Embedding JavaScript Strings from an ASP.NET Page
by Rick Strahl August 22, 2007 @ 11:12am
EncodeJsString will return a string in the format of "string" so an apostrophy is not an issue. IOW, it returns the quote as part of the string so typically nothing else is required to format the string.
# re: Embedding JavaScript Strings from an ASP.NET Page
by espinete November 23, 2007 @ 3:34am

if (i < 32 || i > 127)
{
sb.AppendFormat("\\u{0:X04}", i);
}
else
{
sb.Append(c);
}

Why not use \\uXXX for characters 32 to 127 ??

Thanks in advance.
# re: Embedding JavaScript Strings from an ASP.NET Page
by Rick Strahl November 23, 2007 @ 10:25am
Because you make the size of the string 5 times as large as a single character? Because it's not readable?
# re: Embedding JavaScript Strings from an ASP.NET Page
by myro November 07, 2008 @ 2:49am
hello sir,
you forgot:

case '\'':
sb.Append("\\\'");
break;

thx for sharing your code, and have a nice day :)
# re: Embedding JavaScript Strings from an ASP.NET Page
by Rick Strahl November 07, 2008 @ 10:38am
@myro - single quotes don't need encoding in JSON because the outer delimiter is a double quote. Inner single quotes are safe.
# re: Embedding JavaScript Strings from an ASP.NET Page
by Rick Strahl November 07, 2008 @ 10:44am
@espinente - >> Why not use \\uXXX for characters 32 to 127 ??

Because it would mean that your JSON size would bloat by 4x the size of the original content.
# re: Embedding JavaScript Strings from an ASP.NET Page
by neal kernohan December 03, 2008 @ 7:37am
Thanks Rick, I need the apostrophe handled so added it for my usage. Server.HtmlEncode and HttpServerUtility(?) were no good for me. Thanks for the help, another one for the helper classes.
# re: Embedding JavaScript Strings from an ASP.NET Page
by Rick Strahl December 03, 2008 @ 11:42am
@neal @myro - I am really curious why you'd need the ' encoded. It's not necesary and won't save you if you have nested strings (it'll still think the single quote will be end of string in that case).

So where is the ' a problem unencoded and does encoded really solve that problem if there is one?
# re: Embedding JavaScript Strings from an ASP.NET Page
by neal kernohan December 03, 2008 @ 11:59pm
@rick Note that this was not used for JSON in my case, but simply for passing a string from c# to client side javascript. The string of course, orginating from c#, hence the need for the encoding.

Regardless, *you are indeed correct* and thank you for prompting me to look closer at my own code. The error of my ways was not changing the legacy code in place, but rather doctoring your code to suit. I realise now that your code above works just swell and my implemenatation of it was at fault. After many years of surrounding strings in single quotes (apostrophes) for javascript I had left them in place. No need. To illustrate, in a simplified version, what I had was:

ClientScript.RegisterStartupScript(typeof(string),
"openFileError",
"alert(\'" + Server.HtmlEncode(ex.Message) + "\');", true);


I removed the surrounding quotes from your method and replaced this with:

ClientScript.RegisterStartupScript(typeof(string),
"openFileError",
"alert(\'" + JavascriptHelper.EncodeJsString(ex.Message) + "\');", true);


Using the helper you have provided exactly as is, the *correct* implementation, after a new start and a fresh coffee is, of course:

ClientScript.RegisterStartupScript(typeof(string),
"openFileError",
"alert(" + JavascriptHelper.EncodeJsString(ex.Message) + ");", true);


I thank you again Rick, your implementation is correct. 'Error between computer and chair', as they say.
# re: Embedding JavaScript Strings from an ASP.NET Page
by Rick Strahl December 04, 2008 @ 12:07am
@neal - no worries. I just wanted to make sure I didn't miss something since you were the second person on this thread that had mentioned this very issue.

Glad it works as advertised... :-}
# re: Embedding JavaScript Strings from an ASP.NET Page
by Rob January 12, 2009 @ 7:56am
Thanks Rick, found your article when I was looking to see if this functionality was built into .NET already before writing my own. Very useful.

I was wondering if this could be used to encode CDATA closing tags and came up with the following code to extend your functionality:-

    case ']':
      sb.Append("\\]");
      break;


This should stop JavaScript enclosed in a CDATA tag having the CDATA closed by user input containing ]]>
# re: Embedding JavaScript Strings from an ASP.NET Page
by Rick Strahl January 12, 2009 @ 11:29am
@Rob - I don't follow what you're saying. ] is not a a character that needs to be encoded. If the issue is that your XML encoder/parser falls down on this then you should deal with that separately - otherwise you could come up with a million rules for other applications that can't read strings that contain certain chars or char combinations :-}
# re: Embedding JavaScript Strings from an ASP.NET Page
by Rob January 13, 2009 @ 3:26am
@Rick - Sorry, I didn't explain that very well! I'll try explain in more detail below:-

Suppose you have the following code:-

string markup = wwWebUtils.EncodeJsString("Some text");

string script = @"
embedHtml({0});
function embedHtml(result)
{{
    alert(result)
}}";


This renders in ASP.NET 3.5 as:-

<script type="text/javascript">
//<![CDATA[

embedHtml("Some text");
function embedHtml(result)
{
  alert(result)
}//]]>
</script>

All well and good. But suppose the text contains the ]]> sequence (end of a CDATA tag):-

string markup = wwWebUtils.EncodeJsString("Some text]]>");


This will cause the HTML to render as:-

<script type="text/javascript">
//<![CDATA[

embedHtml("Some text]]>");
function embedHtml(result)
{
 alert(result)
}//]]>
</script>


Although the alert box displays as it should, this produces invalid XHTML because the ]]> sequence in the embedHtml function call closes the CDATA tag. The reason for my encoding of the ] character was to avoid the ]]> appearing as a literal in the produced code. This still decodes correctly in JavaScript as well as producing valid XHTML:-

<script type="text/javascript">
//<![CDATA[

embedHtml("Some text\]\]>");
function embedHtml(result)
{
  alert(result)
}//]]>
</script>


I'd be interested in hearing your comments. As you say, it is best to avoid a million rules but if you didn't add ] encoding in this function then you'd have to add it somewhere else which would mean a double function call every time you wish to JS encode something. I await your reply with interest!
# re: Embedding JavaScript Strings from an ASP.NET Page
by Rick Strahl January 13, 2009 @ 9:47am
@Rob - Yeah I figured it was something along those lines of embedding the CDAtA end tag into the document, but a) that's clearly a bug in the browser (which should recognize the quotes) and b) I still think this should be handled in the specific case. ]]> can't be a string that gets used for a string literal very frequently. :-}
# re: Embedding JavaScript Strings from an ASP.NET Page
by Rob January 13, 2009 @ 10:33am
@Rick. Cheers for your reply. Suppose a better solution would be to code for the specific case like splitting the literal up with concatenation instead of encoding.

I wouldn't say its a bug in the browser as surely a CDATA tag denotes that a section shouldn't be parsed, therefore it shouldn't be looking for quotes either?

As you say it wouldn't be a common occurrence, I just noticed this was possible as ways of escaping a string can sometimes point to security vulnerabilities. But since JavaScript is client side I can't see any advantage gained by escaping a JavaScript string value anyway.
# re: Embedding JavaScript Strings from an ASP.NET Page
by Aelx B Clarke February 07, 2009 @ 7:46am
Thanks, Rick. Saved me a good few hours!!!
# re: Embedding JavaScript Strings from an ASP.NET Page
by Paresh February 09, 2009 @ 2:09pm
Thanks for this Rick - saved me a few hours of work and not too many folks trying to solve these types of problems.

Cheers.
# re: Embedding JavaScript Strings from an ASP.NET Page
by Josh Stodola March 10, 2009 @ 4:40pm
Interestingly enough, Rick, I came across an escape function in Microsoft.JScript.dll today! It's in version 2.0 of the framework under Microsoft.JScript.GlobalObject. What's more surprising is that I actually remembered the comments made ~18 months ago!

Reflector gives me:
[NotRecommended("escape"), JSFunction(JSFunctionAttributeEnum.None, JSBuiltin.Global_escape)]
public static string escape(object @string)
{
    string str = Convert.ToString(@string);
    string str2 = "0123456789ABCDEF";
    int length = str.Length;
    StringBuilder builder = new StringBuilder(length * 2);
    int num3 = -1;
    while (++num3 < length)
    {
        char ch = str[num3];
        int num2 = ch;
        if ((((0x41 > num2) || (num2 > 90)) &&
             ((0x61 > num2) || (num2 > 0x7a))) &&
             ((0x30 > num2) || (num2 > 0x39)))
        {
            switch (ch)
            {
                case '@':
                case '*':
                case '_':
                case '+':
                case '-':
                case '.':
                case '/':
                    goto Label_0125;
            }
            builder.Append('%');
            if (num2 < 0x100)
            {
                builder.Append(str2[num2 / 0x10]);
                ch = str2[num2 % 0x10];
            }
            else
            {
                builder.Append('u');
                builder.Append(str2[(num2 >> 12) % 0x10]);
                builder.Append(str2[(num2 >> 8) % 0x10]);
                builder.Append(str2[(num2 >> 4) % 0x10]);
                ch = str2[num2 % 0x10];
            }
        }
    Label_0125:
        builder.Append(ch);
    }
    return builder.ToString();
}
# re: Embedding JavaScript Strings from an ASP.NET Page
by Rick Strahl May 07, 2009 @ 12:51pm
@Josh - that code is for HTMLEncoding which isn't the same as JSON encoding of strings for use in JavaScript. That function would yield some uh, undesirable results.
# re: Embedding JavaScript Strings from an ASP.NET Page
by Igor Ostrovsky May 14, 2009 @ 2:48am
Awesome, this is exactly what I was looking for! Is the code sample in public domain? Am I allowed to use it in an open-source project, with attribution?
# ASP.NET – Converting C# String to JSON String
by Nuno Gomes May 22, 2009 @ 4:09pm
Most web applications display messages to users. Displaying messages is the most effective way to inform
# re: Embedding JavaScript Strings from an ASP.NET Page
by JohnL September 11, 2009 @ 6:16pm
Thanks, a handy function.

I did have to add encoding of single quotes for my use - writing out JavaScript events to be called when clicking on a link, such as:

<a href='#' onclick='selectemployee("O\u0027Hanlon, Fred","fred.ohanlon@example.com");'>O'Hanlon, Fred</a>

The parameters were supplied from variables (in a loop) when building up the html, and so could contain anything.

Without the encoding of the single quote, the bare quote will prematurely end the onclick event.

You need to encode it as \u0027 rather than \\\' as that still prematurely ends the event code.
# re: Embedding JavaScript Strings from an ASP.NET Page
by Brian Hazzard November 05, 2009 @ 6:52am
You removed my last comment? Was it offensive? I thought it was in the spirit of community. OH well...
# re: Embedding JavaScript Strings from an ASP.NET Page
by Gonzalo Sarasola November 11, 2009 @ 8:03am
Rick, hi! I´m new at ASP.NET and I´m having this issue. Is there a way to do it without ussing JSON?

thx
# re: Embedding JavaScript Strings from an ASP.NET Page
by Andrew Deacon December 31, 2009 @ 4:06am
Nice. A thoroughly handy copy and paster. Thanks.
# re: Embedding JavaScript Strings from an ASP.NET Page
by eliza sahoo April 29, 2010 @ 2:29am
In Some cases while displaying a large number it will be nice if we can format the number to a more readable format
Like : Reputation Point : 537456
Can be more readable if we can write it as Reputation Point : 537,456
ASP.NET provide features like String.Format(format,arg0) to format arguments into different forms.
For above solution you can implement

Response.Write(String.Format("{0:#,###}", 123456789));
Which will print 123,456,789

{0:#,###} → Known as the format string where “{ ,}”are compulsory to mentation.
The first part before ':' represent the argument number & it will be an integer.
The second part after ':' represent the format that you want your argument to be converted.
http://www.mindfiresolutions.com/Formating-the-string-before-displaying-in-ASPNET-887.php
# re: Embedding JavaScript Strings from an ASP.NET Page
by techron June 04, 2010 @ 9:36am
I agree with Andrei, the following case may be necessary when there is no guarantee that '\'' is an inner quote. I used it with javascript alert to prevent "A Runtime Error has occurred, Do you wish to Debug? Line X Error: Expected ')'" error.

case '\'':
sb.Append("\\\'");
break;
# re: Embedding JavaScript Strings from an ASP.NET Page
by DK June 07, 2010 @ 7:14am
Hi,

I also agree that escaping single quotes is necessary. Especially when the function is called EncodeJsString and not EncodeJSONStringAndAddAnOuterDelimiter :-)

Anybody has a tip how to escape strings used in JS in events?

when I escape a text containing both quotes I get this which is still not OK.

some ' text " with both quotes

<a onclick="edit('some \' text \" with both quotes ');" >


thanks

Dan
# re: Embedding JavaScript Strings from an ASP.NET Page
by DK June 07, 2010 @ 7:27am
so I've changed \" for me, but I am not very happy from this solution

                    case '\"':
                        //sb.Append("\\\"");
                        sb.Append("&quot;");
                        break;
# re: Embedding JavaScript Strings from an ASP.NET Page
by Cestbienmoi June 21, 2010 @ 9:22am
In attributes, it is easier to use htmlencode.
# re: Embedding JavaScript Strings from an ASP.NET Page
by Bryan July 08, 2010 @ 6:52pm
Hi, I wanted to share a problem I ran into when the string you want to embed contains script tags.
Embedding a string like this won't work:
string embed = "some text with script.  <script type=\"text/javascript\">alert('do something');</script>";

When you embed this string in javascript a bad thing happens:
<script type="text/javascript">
document.write(<%=wwWebUtils.EncodeJsString(embed)%>);
</script>

Which renders this:
<script type="text/javascript">
document.write("some text with script.  <script type=\"text/javascript\">alert('do something');</script>");
</script>

The document.write will not execute and a script error is generated because the browser interprets the "</script>" at the end of the string as the actual end of the outer script.

A possible solution is to encode the less than sign by adding an extra case to the EncodeJsString method:
case '<':
    sb.Append("\\x3c");
    break;


Hope this helps.
-Bryan
# re: Embedding JavaScript Strings from an ASP.NET Page
by Ali.H September 20, 2010 @ 2:36am
the solution was superb. it helped me much.
# re: Embedding JavaScript Strings from an ASP.NET Page
by Rajan March 06, 2011 @ 9:29pm
Solid fix. Works like a charm.
# re: Embedding JavaScript Strings from an ASP.NET Page
by Paul Stickney April 14, 2011 @ 10:39pm
Here is my variant.
It is "free to use, modify, sell", or whatever you feel like.

It addresses a number of the issues:
1) </script> will not break the enclosing <script>
2) ]]> will not break this in CDATA sections
3) Will not add any outside quotes
4) Will pass harmlessly through XML (& is encoded as well)

It is meant to encode literals to Javascript Strings and nothing else. Do not use for URL encoding. Do not use for JSON.

    public class JsEncoder
    {
        static Regex EncodeLiteralRegex;
        // Given a string, return a string suitable for safe
        // use within a Javascript literal inside a <script> block.
        // This approach errs on the side of escaping.
        public static string EncodeLiteral (string value)
        {
            if (EncodeLiteralRegex == null) {
                // initial accept "space to ~" in ASCII then reject quotes 
                // and some XML chars (this avoids `</script>`, `<![CDATA[..]]>>`, and XML vs HTML issues)
                // this allows / non-escaped, which is against JSON
                var accepted = Enumerable.Range(32, 127 - 32)
                    .Except(new int[] { '"', '\'', '\\', '&', '<', '>' });
                // pattern matches everything but accepted
                EncodeLiteralRegex = new Regex("[^" +
                    string.Join("", accepted.Select(c => @"\x" + c.ToString("x2")).ToArray())
                    + "]");
            }
            return EncodeLiteralRegex.Replace(value ?? "", (match) =>
            {
                var ch = (int)match.Value[0]; // only matches a character at a time
                switch (ch) {
                    case '"': return @"\""";
                    case '\'': return @"\'";
                    case '\\': return @"\\";
                    case '\b': return @"\b";
                    case '\f': return @"\f";
                    case '\n': return @"\n";
                    case '\r': return @"\r";
                    case '\t': return @"\t";
                    default:
                        return ch <= 127
                            ? @"\x" + ch.ToString("x2") // not JSON
                            : @"\u" + ch.ToString("x4");
                }
            });
        }
    }
# re: Embedding JavaScript Strings from an ASP.NET Page
by aishel May 19, 2011 @ 5:40am
Hey chuck, aren't the 3rd and 4th lines from bottom to top switched?
instead of
sb.Append("\""")
Next

should be
Next
sb.Append("\""")
# re: Embedding JavaScript Strings from an ASP.NET Page
by Shukhrat Nekbaev May 19, 2011 @ 2:17pm
Hi,

Also worth looking at .NET Framework 4.0's HttpUtility.JavaScriptStringEncode()
# re: Embedding JavaScript Strings from an ASP.NET Page
by Ketan May 04, 2012 @ 3:40am
Your each article is life saver. thank you.
# re: Embedding JavaScript Strings from an ASP.NET Page
by Nel May 30, 2012 @ 5:28am
Thanks, it helped me a lot.

I was having an issue with single quotes. My text consisted of html tags as well as normal text.

I am using Asp.net C sharp.

I defined the hyperlink tag from code behind.

The onclick event's handler had to be enclosed in single quotes ('') otherwise the tags in the parameters were interpreted as the end of the hyperlink tag.



<a href='javascript:void(0);'
 onclick='test(" + a + "," + encoded_b + "," + encoded_c + ")'" + ">Click Here</a>
.

Now any single quotes in the text produced errors.

So i encoded the single quote character using:

 case '\'':
 sb.Append("&#x27;");
  break;
.

I am a noob , I don't know much about JSON, your code helped me a lot, thanks again.
# re: Embedding JavaScript Strings from an ASP.NET Page
by Cameron Usman August 27, 2012 @ 7:04pm
Thanks Paul Stickney. The JsEncoder class works perfectly to convert literal to JavaScript Strings.

For URL, I use Server.UrlEncode
For JSON, I use Json.Encode

Since these are part of ASP.Net Web Pages (http://www.asp.net/web-pages/overview/more-resources/asp-net-web-pages-api-reference)

Thanks also to Rick Strahl for providing a custom JsonEncoder class and relevant discussions here which I found educational.
 


West Wind  © Rick Strahl, West Wind Technologies, 2005 - 2014