Calling javascript function from c# code behind

In this asp.net tutorial you will learn how to call javascript function from c# code behind. While using asp.net 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.

Calling_javascript_Function.aspx

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

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


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

<body>
<form id="form1" runat="server">
<div>
<table width="100%" cellpadding="2" cellspacing="2" border="0" class="fontclass">
<tr>
<td width="20%"> </td><td><h2>Signup Form</h2></td>
</tr>
<tr>
<td><strong> First Name</strong></td><td><asp:TextBox ID="txt_Firstname" runat="server" EnableTheming="false" Width="150px" Text="Adeel Fakhar"></asp:TextBox> </td>
</tr>
<tr>
<td> </td><td><asp:Button ID="btn_Signup" runat="server" EnableTheming="false" Text="Register"/> </td>
</tr>
</table>
</div>
</form>
</body>
</html>
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.

Calling_javascript_Function.aspx.cs

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

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.

1 comments:

  • Anonymous
     

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

    Refer to below links for more details about the same.

    http://www.a2zmenu.com/CSharp/Calling%20JavaScript%20function%20from%20CSharp.aspx