开发者

javascript: how do I pass safe strings to an array for client side display without messing it up / ASP.NET C#

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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜