Call JavaScript function from CodeBehind in ASP.Net (C# & VB.Net)

Mohammed Imtiyaz Jan 13, 2015

This tutorial will explain you how to call JavaScript function from CodeBehind (C# or VB.NET)

Call JavaScript function from CodeBehind in ASP.Net

ASP.Net Controls

First we will write a JavaScript function "popup" after the head tag of the web page.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="VC.aspx.cs" Inherits="_VC" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
	<script language="javascript" type="text/javascript">
		function popup() {
			var objMessage = "Popup message";
			alert(objMessage);
		}
	</script>
</head>
<body>
	<form id="form1" runat="server">
		<asp:Button ID="btnClickHere" runat="server" Text="Click Here" onclick="btnClickHere_Click" />
	</form>
</body>
</html>

C#

Now call the JavaScript function from C# CodeBehind. The syntax is mentioned below

protected void btnClickHere_Click(object sender, EventArgs e) {
    ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "Title", "<script type='text/javascript'>popup();</script>", false);
}

VB.Net

Now call the JavaScript function from VB.Net CodeBehind. The syntax is mentioned below

Protected Sub btnClickHere_Click(sender As Object, e As System.EventArgs) Handles btnClickHere.Click
	ScriptManager.RegisterStartupScript(Me.Page, Me.GetType, "Title", "<script type='text/javascript'>popup();</script>", False)
End Sub