Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I’m trying to call a JavaScript function from Code behind but no luck so far. I tried to add the following snippets inside Page_Load method.

I’ve tried as below

ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "foo", "alert('test22222')", true);

Also as below

Page.ClientScript.RegisterStartupScript(Type.GetType("System.String"), "addScript", "alert('test22222');", true);

None worked for me. Is there anything I’m missing here? I would like to show the alert message before loading the page.

Any help appreciated. Thanks.

share|improve this question
 
What do you mean "before loading the page"? –  tomasmcguinness Apr 17 at 9:47
 
before rendering the page perhaps? –  MJM Apr 17 at 9:50
 
RegisterstartupScript will put the Javascript at the very end of the page, so the rendering will have completed (I think) before it's executed. You may better off just including the code in your ASPX page, somewhere near the top. –  tomasmcguinness Apr 17 at 10:07

3 Answers

up vote 1 down vote accepted

you can implement it in page_prerender event

    protected void page_prerender( object sender, EventArgs e )
{
         your code here;
}
share|improve this answer
 
This behaves same as the current one :( –  MJM Apr 17 at 9:51
 
what you want to implement can you elaborate briefly so that we can suggest you an another way out also. –  Rohan Leuva Apr 17 at 9:54
 
I want to call a function before the page renders in the screen. So I tried to implement it. It didn't get called. I even called alert as given in the code that also didn't work. –  MJM Apr 17 at 9:57
 
refer to updated answer –  Rohan Leuva Apr 17 at 10:51
 
Thanks it worked –  MJM Apr 17 at 12:06
show 1 more comments

You are missing a ; in you code. Try this it worked for me.

But i would suggest the ScriptManager.RegisterStartupScript over the Page.ClientScript.RegisterStartupScript as the first one is designed for AJAX calls. Which will work for even partial page post backs.

ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "foo", "alert('test22222');", true);
share|improve this answer

This will work. You forgot semicolon at end of your alert:

ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "foo", "alert('test22222');", true);
share|improve this answer
 
It has no effect :( same behavior –  MJM Apr 17 at 9:57
 
Are you using ajax calls? –  Yeronimo Apr 17 at 10:02

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.