Click here to Skip to main content
15,904,155 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I am writing the javascript in Code behind as follows:

MIDL
string script = "<script language=" + Strings.Chr(34) + "javascript" + Strings.Chr(34) + ">" + "  alert(" + Strings.Chr(34) + msg + Strings.Chr(34) + ");" + "</script>";
       ClientScript.RegisterStartupScript(this.GetType(), "Message", script);



It showing error in the strings.chr. Canany one tell me what is the correct code.

Thanks in advance
Posted
Comments
thatraja 11-Jul-11 3:05am    
what's the error message?

Who told you there is Strings and Strings.Chr? It's probably from your previous re-incarnation.

Do you mean just a character with Unicode code point 34? This is just a quotation mark!

Use:
C#
string script = @"<script language=""javascript""> and so on...";


The symbol "@" means verbose syntax for string literal; in this syntax, quotation mark is escaped by doubling it. In regular syntax, it is escaped as \".

A character from numeric literal meaning its code point can be obtained as (char)34. You don't need it here.

Why not simply referring to C# reference instead of your trial-and-error? So counter-productive!

Also, avoid multiple concatenation of strings (+). Is is very ineffective because string is immutable. (Do I have to explain why?) If you concatenate just constants, it would not matter, because it's done in compile time, but if you used function in between, it would be during run-time.

Use string.Format instead. If concatenated members are statically unknown, use System.Text.StringBuilder.

Avoid any immediate constants, especially strings. Use explicit constants, resources, data files, etc.

—SA
 
Share this answer
 
v3
Comments
Prerak Patel 11-Jul-11 3:27am    
5, well explained.
Sergey Alexandrovich Kryukov 11-Jul-11 3:48am    
Thank you very much, Prerak.
--SA
Use it like this

string script = "<script language='javascript'> alert('" + msg + "');</script>";<br />
ClientScript.RegisterStartupScript(this.GetType(), "Message", script);
 
Share this answer
 
v5
Comments
Sergey Alexandrovich Kryukov 11-Jul-11 3:18am    
Sorry, this is incorrect. You're using non-escaped " in string literal -- it won't compile. Also you're using multiple '+'. My 1 this time, sorry.
--SA
Prerak Patel 11-Jul-11 3:20am    
Ah, my bad. Actually I forgot to change it to single quotes.
Sergey Alexandrovich Kryukov 11-Jul-11 3:21am    
I actually did not vote yet -- please fix it.
Please see my answer.
--SA
Prerak Patel 11-Jul-11 3:26am    
Seems like a bug in pre tag. If I write 'javascript', it displays "'javascript'" (enclosed in double quotes). Used code tag instead.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900