Search This Blog

Sunday, April 8, 2012

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);
    }
}
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();");

1 comment:

  1. Thank you for the thoughtful review. The main advantage of html5 video player seems to be for embedding rich media such as audio and video in modern browsers. Although, the structure elements seem to be useful. CSS3 seems to be headed in the right direction, leaving many possibilities for implementation and creativity,

    ReplyDelete