Tuesday, January 8, 2013

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