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

31 comments:

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

    ReplyDelete
  2. ditto- we registered it, now how do we call it?

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

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

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

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

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

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

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

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

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

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

    }

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

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

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

    ReplyDelete
  16. thanks a lot for this topic

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

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

    ReplyDelete
  19. Very good and well explained articles! Thanks for sharing!

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

    ReplyDelete
  21. 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?

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

    ReplyDelete
  23. How "ganesh" said:

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

    ReplyDelete
  24. @ Musiklehrer Köln

    There must be a mistake in your code.

    It works fine - every time!

    ReplyDelete
  25. Thank you for sharing your skill

    ReplyDelete
  26. 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?

    ReplyDelete
  27. 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!

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

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

    ReplyDelete
  30. // 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);

    ReplyDelete