views:

97

answers:

5

I am creating a javascript confirm message in my asp.net code:

deleteButton.Attributes.Add("onclick", "javascript:return confirm('Are you sure you want to delete client " + clientName + "')");

The problem here is that the client name can have apostrophes and other problematic characters.

Does anyone know a good, simple way to clean the variable "clientName" so that I can safely use it in the javascript?

Thanks!

+11  A: 

new JavaScriptSerializer().Serialize(clientName)

ifwdev
Thanks ifwdev! I was expecting a cool regex (which I am sure is out there), but I had no idea this method existed in the framework. Very nice.
Mark Kadlec
Ditto! Thanks for this answer!.
David Stratton
I kenw about this for object serialization, to get JSON objects out of plain old CLR objects, but never thought of using it for this purpose...nice!
Jonas
+1  A: 

I'm not sure how to do it in .net but rule number one with user input is not to clean, but to escape it.

Otherwhise users won't be able to have " in their usernames (might not be so common but in other situations, like this response to your question i had a very legitmate reason to include a ")

Erik
Good point Erik, looks like Nicolas put the code below. Very relevant when not using names for sure! I learned two things from one post, today is a good day...
Mark Kadlec
+1  A: 

I'm sure you've thought of this, but the .Replace()function is about as simple as it gets.

deleteButton.Attributes.Add("onclick", "javascript:return confirm('Are you sure you want to delete client " + clientName.Replace("'", "&_#39" + "')");
David Stratton
I did David, but curiosity had the better of me and just wanted to see what other cool solutions were out there. Surprisingly there wasn't a good thread when I searched the Web but StackOverflow seemed like a good place to start one to get some ideas.
Mark Kadlec
For my similiar situation (passing some data to an ammap from asp.net) this was the only answer that worked...
DaveEHS
+1  A: 

To get a little fancier:

    public static string ToJavascriptString(this string str)
 {
  Dictionary<string, string> replace = new Dictionary<string, string>();
  replace.Add("'", @"\'");
  replace.Keys.ToList().ForEach(s => str = str.Replace(s, replace[s]));
  return str;
 }
Jonas
+1  A: 
SecurityElement.Escape(string s)
Nicolas Dorier