MJM
MJM

Reputation: 89

Call JavaScript function from ASP.net code behind

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.

Upvotes: 2

Views: 1762

Answers (3)

user1776054
user1776054

Reputation:

you can implement it in page_prerender event

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

Upvotes: 1

Guru Kara
Guru Kara

Reputation: 6462

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);

Upvotes: 2

Yeronimo
Yeronimo

Reputation: 1749

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

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

Upvotes: 0

Related Questions