Execute JavaScript function from ASP.NET codebehind

Calling a JavaScript function from codebehind is quiet simple, yet it confuses a lot of developers. Here's how to do it. Declare a JavaScript function in your code as shown below:

JavaScript

<head runat="server">
<
title>Call JavaScript From CodeBehind</title>
<
script type="text/javascript">
function
alertMe() {
alert('Hello');
}
</script>
</
head>

In order to call it from code behind, use the following code in your Page_Load

C#

protected void Page_Load(object sender, EventArgs e)
{
if (!ClientScript.IsStartupScriptRegistered("alert"))
{
Page.ClientScript.RegisterStartupScript(this.GetType(),
"alert", "alertMe();", true);
}
}

VB.NET

If (Not ClientScript.IsStartupScriptRegistered("alert")) Then
Page.ClientScript.RegisterStartupScript _
(Me.GetType(), "alert", "alertMe();", True)
End If

The Page.ClientScript.RegisterStartupScript() allows you to emit client-side script blocks from code behind. More info here http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.registerstartupscript.aspx

To call the JavaScript code on a button click, you can add the following code in the Page_Load

btnCall.Attributes.Add("onclick", " return alertMe();");

Update: This was a very simple example. However comments left by previous users suggest that they want more than this :) If you want to go into details, here are two articles I wrote and strongly recommend

Calling JavaScript from ASP.NET Master Page and Content Pages - Part I

Calling JavaScript from ASP.NET Master Page and Content Pages - Part II






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

31 comments:

Anonymous said...

Great The clearest example of how to declare it but how do you used it?

Anonymous said...

ditto- we registered it, now how do we call it?

Anonymous said...

Thanks for a clear example. This example runs on page load. This is not what I'm after either.

I want to from code behind call a function in javascript, like confirm something. Then if they selected Yes then call back to code behind. The javascript is NOT always called, only if a certain condition is met which is calculated in code behind.

Any thoughts are welcome.

Eye said...

I got to this post googling for an answer on how to run a clientside javascript from code-behind. This example shows how to register a script, not how to execute it. Please change the heading of you post.

Vasil said...

I think the code gets executed on Page_Load as mentioned by the author in this article?

CyberHawke said...

obviously either the author did not understand the topic or has left a step out. As everyone has noted, this example describes the registration of a script from code behind, but does not explain how to interact with the script (once it is registered) from your code behind.

I personally suspect that what we would like to do is not possible since the server needs to be aware of the object or script you want to execute. Think about it, if you place an element on the screen and do not include a "runat" attribute then the server is oblivious of its exsistence. The same would be true of your javascript functions. Unless there is a way to make the server aware that the scripts exist on the page then there is no way for the server to know what is there to call.

Just my two cents.

Anonymous said...

This is the type of answer one gets used to from Microsoft. Tells you what you can do (probably), but not how to do it.

Suprotim Agarwal said...

Apologies for the delay in the reply. I had not subscribed to this post comments and hence did not receive notifications in my mailbox. Apologies once again.

To call the javascript code on a button click, you can add the following code in the page_load

btnCall.Attributes.Add("onclick", " return alertMe();");


I hope this works! Let me know if you face issues

Jerry T. said...

What if you want to call the javascript from an event that's already been fired, such as the RowClicked event of a GridView?

Suprotim Agarwal said...

Jerry: In that case, you would need to capture the OnRowCreated event and add the 'onclick' attribute on each data row

protected void OnRowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onclick", "alertMe()");
}

}

I would although use jQuery to do this now as demoed in my article over here

Some ASP.NET GridView UI Tips and Tricks using jQuery

Luis Roquette Valdez said...

A bit of nonsense if you ask me...
The cool stuff would be to call the javascript method from a click event... not from a clientside click...

nobody said...

Ok, what if you want to call the function you created in the codebehind in the page_load event.

protected void Page_Load(object sender, EventArgs e)
{
hdnEMPID.Value = "000140950";

//RUN JAVASCRIPT AFTER THE FIELD HAS BEEN PROPAGATED.

}

Anonymous said...

very good post

saber said...

This post shows how to introduce javascript in the code behind, and also it can be used to execute the script when calling an event.
Having this code in the page_load() introduces it in our asp page but having it in other method, execute it like a part of the event.
Let's say we want execute this javascript by clicking a button, all we have to do is to integrate this code in the button_click() method, and the script will be executed directly.

maan said...

this function calls on page load, my case is that i have to text boxes and an add button, when button is clicked , i want to get both values and pass these values to java script and then javascript add the values and return the result.

After getting the result i want to store the result in database in the same function where javascript is called

Waiting for reply
Maan
http://www.pakpressads.com

Anonymous said...

For those still looking for an answer, I think the link below should help. It contains content that describes how to declare and call javascript from code-behind on a button click event.
http://www.codeproject.com/KB/aspnet/ClientServer.aspx

Anonymous said...

thanks a lot for this topic

Anonymous said...

thanks so much really after long search i found short cut without calling an event call a java script function

ganesh said...

Ya, Its work fine, but it fires only one time.

Darren said...

Very good and well explained articles! Thanks for sharing!

Anonymous said...

Nice tip.
how do you pass a parameter to the javascript alert from code behind?

designer koeln said...

I need something like this.
It doesnt work

"**textarea name='musterloesung' id='eingabe' \"javascript:onkeydown='setTimeout('addZeile(document.getElementById(\'eingabe\'))',10);'\" style='font-size:14px;' cols='60' rows='2'>" + myreader["Musterloesung"] + "";

Can someone help me?

Metro Style said...

on a site I saw a background color in the alert box. Did anyone know the settings for this?

Musiklehrer Köln said...

How "ganesh" said:

It also works fine by me, but only one time. Why?

webdesign muenchen said...

@ Musiklehrer Köln

There must be a mistake in your code.

It works fine - every time!

mohan143 said...

Thank you for sharing your skill

Steven Cook said...

When I put the register code in my .asp VB language page, I get the following error.
Microsoft VBScript compilation (0x800A0414)
Cannot use parentheses when calling a Sub
/RTNWBrowse.asp, line 65, column 48
(Me.GetType(), "CCCheck", "alertMe();", True)
--------------------------------------------^
Why?

Gabriele Cozzolino said...

How can I get in VB a variable value calculated inside the javascript code? Let's say i want to pass a X value that I produce inside AlertMe, how do I get it in PageLoad event? Thanks!

Unknown said...

dear sir can we enter html textboxes values in database from submitt button(on which javascript is applied) using c# in asp.net.please reply soon as possible

mirthu said...

Using java script how to I access function in code behind vb.net?? to avoid postback

Unknown said...

// If you want to execute on each post back of page or control.

ScriptManager.RegisterStartupScript(this.page, GetType(), "alert", "alert('test');",true);


ScriptManager.RegisterStartupScript(this.chart1, GetType(), "alert", "alert('test');",true);

//If you want to execute only on page load
ClientScript.RegisterStartupScript(GetType(), "alert", "alert('test');", true);