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



Will you give this article a +1 ? Thanks in advance




About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

25 Responses to "Execute JavaScript function from ASP.NET codebehind"
  1. Anonymous said...
    July 8, 2009 at 11:09 AM

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

  2. Anonymous said...
    September 15, 2009 at 7:49 AM

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

  3. Anonymous said...
    October 2, 2009 at 8:50 AM

    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.

  4. Eye said...
    November 19, 2009 at 8:42 AM

    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.

  5. Vasil said...
    November 20, 2009 at 5:53 AM

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

  6. CyberHawke said...
    November 25, 2009 at 11:40 AM

    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.

  7. Anonymous said...
    December 15, 2009 at 8:56 AM

    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.

  8. Suprotim Agarwal said...
    December 17, 2009 at 7:33 AM

    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

  9. Jerry T. said...
    December 17, 2009 at 12:06 PM

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

  10. Suprotim Agarwal said...
    December 17, 2009 at 9:16 PM

    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

  11. Luis said...
    January 8, 2010 at 7:33 AM

    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...

  12. nobody said...
    February 9, 2010 at 1:13 PM

    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.

    }

  13. Anonymous said...
    May 1, 2010 at 12:53 PM

    very good post

  14. saber said...
    June 28, 2010 at 10:02 AM

    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.

  15. maan said...
    July 7, 2010 at 4:00 AM

    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

  16. Anonymous said...
    October 4, 2010 at 6:44 AM

    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

  17. avrail said...
    October 17, 2010 at 10:25 PM

    thanks a lot for this topic

  18. Anonymous said...
    October 18, 2010 at 1:52 AM

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

  19. ganesh said...
    December 10, 2010 at 12:23 AM

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

  20. Darren said...
    May 20, 2011 at 12:12 AM

    Very good and well explained articles! Thanks for sharing!

  21. Anonymous said...
    December 4, 2011 at 7:19 PM

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

  22. designer koeln said...
    February 27, 2012 at 3:57 AM

    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?

  23. Metro Style said...
    September 4, 2012 at 9:38 AM

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

  24. Musiklehrer Köln said...
    January 23, 2013 at 7:43 AM

    How "ganesh" said:

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

  25. webdesign muenchen said...
    January 23, 2013 at 7:45 AM

    @ Musiklehrer Köln

    There must be a mistake in your code.

    It works fine - every time!

 

Copyright © 2009-2014 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions