Calling javascript function from c# code behind

In this tutorial you will learn how to call javascript function from c# code behind. While using with c# sometimes you may need to call javascript function from c# code behind. Let’s look over how to do this.

I am going to develop a web page in which I will have a form that contains two form fields, one will be asp textbox and other will be asp button. Let’s look over the code of that webpage.


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="MainFolder_SubFolder_Default" %>

<head runat="server">
<title>Calling javascript function from c# code behind

<script language="javascript" type="text/javascript">
function getAlert()
var firstname;
firstname=document.getElementById("<%=txt_Firstname.ClientID %>").value;
return false;

<form id="form1" runat="server">
<table width="100%" cellpadding="2" cellspacing="2" border="0" class="fontclass">
<td width="20%"> </td><td><h2>Signup Form</h2></td>
<td><strong> First Name</strong></td><td><asp:TextBox ID="txt_Firstname" runat="server" EnableTheming="false" Width="150px" Text="Adeel Fakhar"></asp:TextBox> </td>
<td> </td><td><asp:Button ID="btn_Signup" runat="server" EnableTheming="false" Text="Register"/> </td>
Now let’s have a look over its c# code behind file. You just have to put single line of code in Page_Load() function and that’s it.


using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

public partial class MainFolder_SubFolder_Default : System.Web.UI.Page

protected void Page_Load(object sender, EventArgs e)
btn_Signup.Attributes.Add("onClick", "return getAlert()");

I just wanted to call the javascript function which is in mycase getAlert() from asp button’s onClick client side event and for this I use this line of code

btn_Signup.Attributes.Add("onClick", "return getAlert()");

btn_Signup is the id of asp button that I am using in my form. After this I used c# built in method Focus() so that when page loads focus must goes to the asp textbox.

So this is the way to call the javascript function from c# code behind.

Happy Coding, Kepp coding.


  • Anonymous

    You can ClientScriptManager clss method RegisterClientScriptBlock or RegisterStartupScript method to invoke JavaScript Method.

    Refer to below links for more details about the same.