Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ' inside a c# string that launch a javascript function

Tags:

javascript

c#

I'm looking to do this :

ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "alert('Vous n'avez pas les droits d'accès à cette application.');", true);

There is no way to formulate this french sentence without ' :

'Vous n'avez pas les droits d'accès à cette application.'

Javascript fail because (probably) when encountering that caracter it expect it to be the end of the string.

I tried lots of thing like \' and ''' but... no luck...

like image 308
Antoine Pelletier Avatar asked Dec 03 '22 15:12

Antoine Pelletier


1 Answers

You could try this one:

"alert(\"Vous n'avez pas les droits d'accès à cette application.\");"

Why this works?

  • Τhe apostrophe character, ', should be included in double quotes. Otherwise, if you use apostrophes and place between them your string, the string can't be interpeted correctly by the JavaScript engine.
  • We use the backslash character in order we define properly our string in C#, avoiding the double quotes, which is used, when we want to declare a string. Formally, this is called special characters escaping. Please have a look here.

For instance try to type this in the console of your browser (press F12 to go to the developer tools and the click on the console tab)

alert('Vous n'avez pas les droits d'accès à cette application.');

You will notice that 'Vous n' is interpreted as a string and of course you will; get the error that you have already mentioned in your answer. This may help you visualize the above.

like image 194
Christos Avatar answered Jan 02 '23 05:01

Christos