Quite often you need to pass string values from your server side code into JavaScript code. The strings may include special characters, so the following code will produce JavaScript errors and has cross-site scripting vulnerability:
var text = "<%= "This\t is a \"test\"\n string " %>";
alert(text);
To pass values correctly you need to encode all special characters. In .NET 3.5 a new class DataContractJsonSerializer was added to encode server objects into JSON values. The following function is using DataContractJsonSerializer to encode string value:
public string CreateJSONString(string str)
{
var json = new DataContractJsonSerializer(typeof(string));
using (var ms = new MemoryStream())
using (var writer = JsonReaderWriterFactory.CreateJsonWriter(ms))
{
json.WriteObject(ms, str);
writer.Flush();
return Encoding.UTF8.GetString(ms.ToArray());
}
}
So in your .aspx page the following would be used instead:
var text = <% = CreateJSONString("This\t is a \"test\"\n string ") %>;
alert(text);

As you can see, now string value is converted correctly into JavaScript string including double quotes, tab and new line characters.