I am using this code to create a string of javascript code, and running them from C# code behind.
It is working fine for normal values, but breaking when ' (apostrophe) is there in the values.
StringBuilder sb = new StringBuilder();
sb.Append("<script>");
// Store transmission chrome feature.
for(int i=0; i < Transmission.Length; i++)
{
sb.Append("var obj = {text: '" + Transmission[i][0] + "',"
+ "value: '" + Transmission[i][1] +"'};");
sb.Append("transChromeData.push(obj);");
}
sb.Append("</" + "script>");
this.RegisterStartupScript("Info", sb.ToString());
It will also break if someone adds a
\as the value. You need to escape characters which will break a Javascript string - the HttpUtility.JavaScriptStringEncode will do this for you:For archaic versions of .NET, you'll need to roll your own. Rick Strahl has a good implementation which covers different JS characters: