Overview: I want to know the best/easiest way to make arbitrary text data
safe for programmatic insertion into javascript.
Detail: I'm plotting database data onto maps by looping through my records,
building up a javascript statement using stringbuilder, and injecting that
into my page:
***
StringBuilder sb = new StringBuilder();
...[ORM stuff deleted] ..
foreach (Locations loc in locoll)
{
currlocstring = ("AddPin(" + loc.Latitude + "," + loc.Longitude
+ ",null,'" + loc.Name + "','" + loc.Name.Replace("''", "") + "');");
sb.Append(currlocstring);
}
string myScript = "<script type='text/javascript'> ... sb.ToString() + "
</script>";
Page.ClientScript.RegisterStartupScript(this.GetType(), "myscript",
myScript);
***
loc.Name is arbitrary data entered via a form. If the user enters script
characters like apostrophes, it breaks the rendered javascript. I am
wondering if there is an "all in one" sanitizer script inside or outside the
.NET framework that will handle all problematic characters.
Any help out there in netland?
Thank you,
-KF
bruce barker - 17 Aug 2007 15:59 GMT
you can write a javascript quoting function, or the easiest is to use a
hidden field that both can access, then .net will handling the quoting.
public static string JscriptQuote(string s)
{
s = s.Replace("'", "\\'");
s = s.Replace("\n", "\\n");
s = s.Replace("\r", "");
return "'" + s + "'";
}
-- bruce (sqlwork.com)
> Overview: I want to know the best/easiest way to make arbitrary text data
> safe for programmatic insertion into javascript.
[quoted text clipped - 28 lines]
>
> -KF
kenfine@nospam.nospam - 17 Aug 2007 16:46 GMT
Thank you Bruce. Can you discuss this tactic involving the hidden field a
little more? I've never heard of it. Are you saying you would
programmatically load the text data into a hidden field, and then drag it
out again, and that process would sanitize the data?
How exactly would you do this in code?
-KF
> you can write a javascript quoting function, or the easiest is to use a
> hidden field that both can access, then .net will handling the quoting.
[quoted text clipped - 42 lines]
>>
>> -KF