There are times when you want to call a javascript function from code behind based on business logic in your ASP.Net applications. This could be because that your business logic needs to talk to database to decide whether javascript function has to be called or not.

When you do a simple Google search for this problem, you would find out that you can use Page.RegisterStartup method or Page.RegisterClientScriptBlock.

The syntax of the RegisterStartupScript method is

Page.ClientScript.RegisterStartupScript(this.GetType(), "JsFunc", "alert('Hello!')",true);

But this article is about understanding the fundamentals so that you would know ‘How it works’. ASP.Net Web Forms simulates the statefulness and events driven programming like Windows Forms development which is not true. Rob Conrey even calls ASP.Net Web Forms ‘a lie’.

Knowing the fundamentals to see the truth behind the ‘lie’ is necessary if you are working several hours a week on Web Forms. All the below 3 links point to the same article which covers the fundamentals. Please read it – I will wait till you come back.

Read it? OK. Now let us concentrate on solving the problem at our hand. As Charles Kettering said – A problem well stated is a problem half – solved. Let us “half-solve” the problem.

Problem Statement : We want to call javascript from our ASP.Net code-behind.

You may wonder how we can do that – as just now we saw that javascript works on client side and ASP.Net code-behind resides at the server side. But if you are closely following, we also saw that HTML,CSS and Javscript code can be sent to the client from the server side when user is making the request. Yup, you got it. If you want to call javascript function from our ASP.Net code-behind, you should send/calling instructions the javascript code from server side ASP.Net method.

Let us consider a simple web application in which user enters his age. We should tell the user whether he/she is eligible to vote. Of course, you can achieve this functionality at client side itself with HTML and a tiny javascript function – No server side ASP.Net code is required. Now let us assume that this involves very complex business logic where we need to talk to the database to find out whether he is eligible to vote or not 🙂

I have created a simple ASP.Net webform application so that you can user can enter his age.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="VotingEligibilityChk.aspx.cs" Inherits="CallingJsFromCodeBehind.VotingEligibilityChk" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <table> <tr> <td>Enter you age:</td> <td><asp:TextBox ID="txtAge" runat="server"></asp:TextBox></td> </tr> <tr> <td colspan="2"><asp:Button ID="btnValidate" runat="server" Text="Validate" OnClick="btnValidate_Click" /></td> </tr> </table> </div> </form> </body> </html>

I have not written any code-behind code and I just run the application.

Javascript function for our VotingEligibility Check. You can see the generated HTML code by pressing ‘Ctrl U’ in Google chrome or F12 in Internet explorer.

Now let us add some code to check the age and inject the javascript code. I wrote couple of methods – one for finding his eligibility to vote(which simulates complex business logic) and another for injecting the relevant javascript code.

private int ComplexBusinessLogic() { int returnValue =0,age=0; if (Int32.TryParse(txtAge.Text, out age)) returnValue = age>=18 ? 1 : 0; else returnValue = -1; return returnValue; }

Using the RegisterStartupScript method we can inject the javascript method to the generated page so that it could be called. It has below 4 parameters

Type : This is the type of the startup script to register. In our case when using this.GetType() would return this Page(VotingEligibility.aspx)

Key : The key of the startup script to register. You can give any unique name(of type string) for this.

Script : This is where you should enter your javascript function. In our case, I am just calling alert function to show the message to user

addscriptTags: You can set this parameter to true so that javascript function can be injected.

Here is the completed code.

protected void btnValidate_Click(object sender, EventArgs e) { int retValue = ComplexBusinessLogic(); if(retValue==1) Page.ClientScript.RegisterStartupScript(this.GetType(), "VoteJsFunc", "alert('Hey!You are legible to vote!')",true); else if(retValue==0) Page.ClientScript.RegisterStartupScript(this.GetType(), "VoteJsFunc", "alert('Sorry.You are not legible to vote')", true); else if(retValue==-1) Page.ClientScript.RegisterStartupScript(this.GetType(), "VoteJsFunc", "alert('Please enter valid age')",true); }

After making the above changes, run the application. Enter the age as 20 and Validate button. An alert button is shown saying that you are eligible to vote.

Don’t stop here. Press ‘Ctrl U’ in your chrome browser, you can see the javascript function that we wrote at the server side at btnValidate event method at the client side.

This is how it works. Thanks for reading this article. You can sign up to my mailing list below so that I can send useful articles straight to your inbox.