2

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.

3
  • What do you mean "before loading the page"? Commented Apr 17, 2013 at 9:47
  • before rendering the page perhaps? Commented Apr 17, 2013 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. Commented Apr 17, 2013 at 10:07

3 Answers 3

2

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);
Sign up to request clarification or add additional context in comments.

Comments

1

you can implement it in page_prerender event

    protected void page_prerender( object sender, EventArgs e )
{
         your code here;
}

2 Comments

This behaves same as the current one :(
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.
0

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

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

1 Comment

It has no effect :( same behavior

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.