Can someone provide good examples of calling a JavaScript function From CodeBehind and Vice-versa?
21 Answers
You may try this :
Page.ClientScript.RegisterStartupScript(this.GetType(),"CallMyFunction","MyFunction()",true);

- 2,448
- 1
- 15
- 17
-
43I would go for the ScriptManager.RegisterStartupScript(Page, typeof(Page), "somekey", script, true); approach. It works during partial postbacks as well. – rdmptn Apr 19 '13 at 12:27
-
101. Sometimes `Page.ClientScript.RegisterClientScriptBlock` is required instead [see this post for info](http://stackoverflow.com/questions/666519/difference-between-registerstartupscript-and-registerclientscriptblock). 2. It might be worth mentioning that in order for MyFunction() to work, MyFunction() has to be defined before the form tags or inside of them, but NOT after the ending tag (otherwise a Object expected error will occur) – BornToCode Aug 22 '13 at 14:53
-
3`ScriptManager.RegisterStartupScript(this.Page, typeof(Page), "text", "openDep()", true);` works. `this.GetType()` throws an error for me. – SearchForKnowledge Apr 16 '15 at 12:34
-
4This not works when the code wrapped with an `asp:UpdatePanel` and written in a button event. Which causes the page to postback. – Senura Dissanayake Jun 22 '18 at 04:40
-
1I know this is an old post, but I am confused on where this code goes. Is it in the C# CodeBehind? Is it in the JS file that has the function? Is it in the aspx page? – Yuval Amir Jun 08 '22 at 22:54
-
It goes in the c# codebehind. Place it where you want the js to be executed. – firewolf006 Sep 26 '22 at 17:17
Calling a JavaScript function from code behind
Step 1 Add your Javascript code
<script type="text/javascript" language="javascript">
function Func() {
alert("hello!")
}
</script>
Step 2 Add 1 Script Manager in your webForm and Add 1 button too
Step 3 Add this code in your button click event
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "Func()", true);

- 3,481
- 1
- 34
- 44
-
1When trying to do this when a GridView row is clicked, it only works when using `ScriptManager` as in this answer, not `Page.ClientScript` as in other answers. Might be related to the `asp:UpdatePanel` comment under the accepted answer. – Chris Nov 21 '19 at 20:32
C# to JavaScript: you can register script block to run on page like following:
ClientScript.RegisterStartupScript(GetType(),"hwa","alert('Hello World');",true);
replace alert()
part with your function name.
For calling C# method from JavaScript you can use ScriptManager
or jQuery
. I personally use jQuery
. You need to decorate the method that you want to call from JavaScript with WebMethod
attribute. For more information regarding calling C# method (called PageMethod
) from jQuery
you can refer to Dave Ward's post.

- 40,053
- 20
- 133
- 188
If you need to send a value as a parameter.
string jsFunc = "myFunc(" + MyBackValue + ")";
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "myJsFn", jsFunc, true);

- 2,130
- 19
- 20
You can not do this directly. In standard WebForms JavaScript is interpreted by browser and C# by server. What you can do to call a method from server using JavaScript is.
- Use
WebMethod
asattribute
in target methods. - Add
ScriptManager
settingEnablePageMethods
astrue
. - Add JavaScript code to call the methods through the object
PageMethods
.
Like this:
Step 1
public partial class Products : System.Web.UI.Page
{
[System.Web.Services.WebMethod()]
[System.Web.Script.Services.ScriptMethod()]
public static List<Product> GetProducts(int cateogryID)
{
// Put your logic here to get the Product list
}
Step 2: Adding a ScriptManager
on the Page
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
Step 3: Calling the method using JavaScript
function GetProductsByCategoryID(categoryID)
{
PageMethods.GetProducts(categoryID, OnGetProductsComplete);
}
To call a JavaScript function from server you can use RegisterStartupScript
:
ClientScript.RegisterStartupScript(GetType(),"id","callMyJSFunction()",true);

- 2,080
- 2
- 19
- 44

- 745
- 3
- 12
-
-
@Rob The `GetProducts()` function is just a code-behind function that would live in a controller in an MVC app, so the tags go on top of whatever function you'd want to put in a controller that you'd be intending to call from JavaScript. – vapcguy Oct 16 '18 at 18:57
-
How is `List
` passed to the client-side javascript function? Does client-side function `OnGetProductsComplete` receive a JSON string as its first parameter? – Tim Jun 22 '22 at 12:14
Another thing you could do is to create a session variable that gets set in the code behind and then check the state of that variable and then run your javascript. The good thing is this will allow you to run your script right where you want to instead of having to figure out if you want it to run in the DOM or globally.
Something like this: Code behind:
Session["newuser"] = "false"
In javascript
var newuser = '<%=Session["newuser"]%>';
if (newuser == "yes")
startTutorial();

- 572
- 3
- 10
- 25
You can use literal:
this.Controls.Add(new LiteralControl("<script type='text/javascript'>myFunction();</script>"));

- 565
- 1
- 7
- 27
-
1But doesn't this just add a script into memory, it doesn't actually run it as well? – Fandango68 Mar 30 '17 at 02:16
Working Example :_
<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage2.Master" AutoEventWireup="true" CodeBehind="History.aspx.cs" Inherits="NAMESPACE_Web.History1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
function helloFromCodeBehind() {
alert("hello!")
}
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<div id="container" ></div>
</asp:Content>
Code Behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace NAMESPACE_Web
{
public partial class History1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, GetType(), "displayalertmessage", "helloFromCodeBehind()", true);
}
}
}
Possible pitfalls:-
- Code and HTML might not be in same namespace
CodeBehind="History.aspx.cs"
is pointing to wrong page- JS function is having some error

- 41,955
- 17
- 205
- 154
-
1Thank you for posting the only working example I could understand how to implement – SendETHToThisAddress Oct 14 '20 at 23:28
You cannot. Codebehind is running on the server while JavaScript is running on the client.
However, you can add <script type="text/javascript">someFunction();</script>
to your output and thus cause the JS function to be called when the browser is parsing your markup.

- 310,957
- 84
- 592
- 636
-
72
-
3I wouldn't consider that calling a method from the server-side code since you don't have a real way to get a return value or specify a callback. – ThiefMaster Apr 20 '11 at 14:15
-
8Aw, sure you can. You can call a postback from your javascript or AJAX anything back. I thought it was funny; I tend to do the same thing--"No, that's impossible. Nobody would even want to do that if they could." then a few minutes later "So here's how we are going to do it." – Apr 20 '11 at 14:19
ScriptManager.RegisterStartupScript(this, this.Page.GetType(),"updatePanel1Script", "javascript:ConfirmExecute()",true/>

- 665
- 7
- 7
IIRC Code Behind is compiled serverside and javascript is interpreted client side. This means there is no direct link between the two.
What you can do on the other hand is have the client and server communicate through a nifty tool called AJAX. http://en.wikipedia.org/wiki/Asynchronous_JavaScript_and_XML

- 851
- 2
- 7
- 24
I've been noticing a lot of the answers here are using ScriptManager.RegisterStartupScript
and if you are going to do that, that isn't the right way to do it. The right way is to use ScriptManager.RegisterScriptBlock([my list of args here])
. The reason being is you should only be using RegisterStartupScript when your page loads (hence the name RegisterStartupScript).
In VB.NET:
ScriptManager.RegisterClientScriptBlock(Page, GetType(String), "myScriptName" + key, $"myFunctionName({someJavascriptObject})", True)
in C#:
ScriptManager.RegisterClientScriptBlock(Page, typeof(string), "myScriptName" + key, $"myFunctionName({someJavascriptObject})", true);
Of course, I hope it goes without saying that you need to replace key with your key identifier and should probably move all of this into a sub/function/method and pass in key and someJavascriptObject (if your javascript method requires that your arg is a javascript object).
MSDN docs:
https://msdn.microsoft.com/en-us/library/bb338357(v=vs.110).aspx

- 539
- 3
- 13
This is how I've done it.
HTML markup showing a label and button control is as follows.
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblJavaScript" runat="server" Text=""></asp:Label>
<asp:Button ID="btnShowDialogue" runat="server" Text="Show Dialogue" />
</div>
</form>
</body>
JavaScript function is here.
<head runat="server">
<title>Calling javascript function from code behind example</title>
<script type="text/javascript">
function showDialogue() {
alert("this dialogue has been invoked through codebehind.");
}
</script>
</head>
Code behind to trigger the JavaScript function is here.
lblJavaScript.Text = "<script type='text/javascript'>showDialogue();</script>";

- 36,151
- 76
- 250
- 438

- 187
- 1
- 4
ScriptManager.RegisterStartupScript(Page, GetType(), "JavaFunction", "AlertError();", true);
using your function is enough

- 41
- 4
-
2
-
1What is this "JavaFunction" parameter ? Can we add anything in it? What needs to have in that argument? – Senura Dissanayake Aug 28 '18 at 12:09
-
1@SenuraDissanayake It's a title-yes, it can be anything & doesn't really matter. – vapcguy Oct 16 '18 at 19:16
Try This in Code Behind and it will worked 100%
Write this line of code in you Code Behind file
string script = "window.onload = function() { YourJavaScriptFunctionName(); };";
ClientScript.RegisterStartupScript(this.GetType(), "YourJavaScriptFunctionName", script, true);
And this is the web form page
<script type="text/javascript">
function YourJavaScriptFunctionName() {
alert("Test!")
}
</script>

- 221
- 11
- 14
this works for me
object Json_Object=maintainerService.Convert_To_JSON(Jobitem);
ScriptManager.RegisterClientScriptBlock(this,GetType(), "Javascript", "SelectedJobsMaintainer("+Json_Object+"); ",true);

- 8,950
- 115
- 65
- 78

- 174
- 1
- 7
Since I couldn't find a solution that was code behind, which includes trying the ClientScript
and ScriptManager
like mutanic and Orlando Herrera said in this question (they both somehow failed), I'll offer a front-end solution that utilizes button clicks to others if they're in the same position as me. This worked for me:
HTML Markup:
<asp:button ID="myButton" runat="server" Text="Submit" OnClientClick="return myFunction();"></asp:button>
JavaScript:
function myFunction() {
// Your JavaScript code
return false;
}
I am simply using an ASP.NET button which utilizes the OnClientClick
property, which fires client-side scripting functions, that being JavaScript. The key things to note here are the uses of the return
keyword in the function call and in the function itself. I've read docs that don't use return
but still get the button click to work - somehow it didn't work for me. The return false;
statement in the function specifies a postback should NOT happen. You could also use that statement in the OnClientClick
property: OnClientClick="myFunction() return false;"

- 1,685
- 1
- 8
- 18
I used ScriptManager in Code Behind and it worked fine.
ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "CallMyFunction", "confirm()", true);
If you are using UpdatePanel in ASP Frontend. Then, enter UpdatePanel name and 'function name' defined with script tags.

- 87
- 1
- 5
Thank "Liko", just add a comment to his answer.
string jsFunc = "myFunc(" + MyBackValue + ")";
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "myJsFn", jsFunc, true);
Added single quotes ('
) to variable, otherwise it will give error message:
string jsFunc = "myFunc('" + MyBackValue + "')";

- 5,031
- 17
- 33
- 41

- 115
- 10
You can't call a Javascript function from the CodeBehind, because the CodeBehind file contains the code that executes server side on the web server. Javascript code executes in the web browser on the client side.

- 6,815
- 5
- 41
- 64
-
1You can't call a javascript function directly as in myCoolJavascriptFunction(javascriptFunctionArgs); on the server, but you can call a javascript function from the code behind in a WebForms page. – cr1pto May 12 '17 at 15:31
-
You can expose C# methods on codebehind pages to be callable via JavaScript by using the ScriptMethod attribute.
You cannot call JavaScript from a CodeBehind - that code exists solely on the client.

- 27,301
- 27
- 95
- 148