Ruslan
Ruslan

Reputation: 3058

Escape variable for JavaScript in asp.net

I have the following code in asp.net:

string backToParentFunc = string.Format("backToParent('{0}', '{1}', '{2}', '{3}');",
                                              Server.UrlEncode(login),
                                              Server.UrlEncode(firstName),
                                              Server.UrlEncode(lastName),
                                              Server.UrlEncode(email);
ScriptManager.RegisterStartupScript(this, GetType(), "backToParent", backToParentFunc, true);

Of course it stops working when the "lastName" variable contains ['] symbol (O'Connell). How to correctly escape strings in asp.net to make them appear correctly in JavaScript code?

Upvotes: 0

Views: 578

Answers (2)

Michael Liu
Michael Liu

Reputation: 55519

Consider using the JavaScriptEncode method from the Microsoft Anti-Cross Site Scripting Library.

Upvotes: 4

bang
bang

Reputation: 5221

You can do a lastName.Replace("'", "\"").

Upvotes: 0

Related Questions