Calling a javascript function from a codebehind

  • Thread starter Thread starter Jan Eliasen
  • Start date Start date
J

Jan Eliasen

Hi

I have an ImageButton on my webpage. It is on a .ascx-page and I have
a .ascx.cs behind this file. I need to be able to call a
javascript-function in my codebehind. When the user presses the
ImageButton, I want something done, and then if this goes well, a
certain javascriptfunction should be called.

I tried adding this to my function in my codebehind;

string myScript = "<script
language=Javascript>aliert('Testing');</script>";
Page.RegisterClientScriptBlock("mailsent", myScript);

And this works great. But I simply cannot figure out how to have
linebreaks in the text the alert-box shows. If I add a "\n" to the
text, then I get an "Unterminated string" error.

Any ideas? Everything is appreciated!
 
Jan,

If you add \n, then .NET will interpret that as a new line character on
the server. This sends a new line character to the client. If you want to
get around this, you have two choices. You can choose to treat the string
literally, like this:

// Notice the "@". This means treat the string literally, so your \n won't
be considered an escape sequence.
string myScript = @"<script language=Javascript>alert('Testing\nNew
line!');</script>";

// Or escape the "\"
string myScript = "<script language=Javascript>alert('Testing\\nNew
line!');</script>";

Hope this helps.
 
On Thu, 11 Mar 2004 09:00:54 -0500, "Nicholas Paldino [.NET/C# MVP]"

And ten points go to the lifesaver Nicholas! :-)
 
Back
Top