2011-04-24

.NET: Executing Javascript From 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 CodeBehindtitle>
<
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();");