views:

40

answers:

1

platform: ASP.NET 3.5 / C#

My requirement is this:

I want to create a rather large array on the server side (in C#) and pass it to the browser via

Page.ClientScript.RegisterArrayDeclaration("gBank", js);

My array is a 2-dimension array, and I am constructing it right to pass it to the client. Simple cases work fine.

My problem is the content of the array - there are several strings, for e.g.

[[4, 'hello there', 'this is \n one'],[5,'again','there's another string']] etc. 

These strings can have new lines, ',- and other such characters including < > etc. I did a replace '\n' with '\n' and that was fine, but other characters like ' mess up the array string in the client side.

How do I pass these strings 'safely' so that the array is not messed on the client side, and the content displays as-is?


I found this code on Rick Stahl's blog

http://www.west-wind.com/weblog/posts/114530.aspx

and it seems to work pretty well.

+1  A: 

You need to properly escape your Javascript string literals when building the JSON.

You can use the WPL and call Encoder.JavaScriptEncode.

However, it would be better to use a proper JSON encoder, such as the JavaScriptSerializer class

SLaks
Some JSON encoders do not encode codepoints U+2028 and U+2029 which are newlines in JavaScript, but not in JSON. If you use a JSON library and are going to embed the result in JavaScript, check that "\u2028\u2029" works in your app.
Mike Samuel
Thanks for your replies - see my edit, that link gave a simple but workable solution
jeremy
+1 **"Use a proper JSON encoder"** Then you can do more with the same.
pst