//*
<script type="text/javascript" language="javascript">
function helloWorld(){
alert("welcome to codepedia.info");
}
</script>
//*
Code to call javascript function from C# on pageLoad
Using the below-given code we able to call the javascript function from server-side.
//*
ClientScript.RegisterStartupScript(GetType(), "Javascript", "javascript:FUNCTIONNAME(); ", true);
//*
as our javascript function name as helloWorld() so we write this code as
//*
ClientScript.RegisterStartupScript(GetType(), "Javascript", "javascript:helloWorld(); ", true);
//*
If you have used Asp.net UpdatePanel control from ajax toolkit in your design web page then the code for calling javascript function would be like as written below .i.e using ScriptManager.RegisterStartupScript
//*
ScriptManager.RegisterStartupScript(GetType(), "Javascript", "javascript:FUNCTIONNAME(); ", true);
//*
as our javascript function name as helloWorld() so we write this code as
//*
ScriptManager.RegisterStartupScript(GetType(), "Javascript", "javascript:helloWorld(); ", true);
//*
Conclusion: This is how in Asp.net C# we able to call any javascript function from code-behind may be on page load or on button click. Hope you enjoyed this tutorial. If you have any recommendations, please let us know what you think in the comment section below! See you again next time!
10 comments on “Call Javascript Function from Code Behind in Asp.net C#”
Very useful, thanks.
Just want to mention that this will fail if your code behind (i.e. Response) is returning a download instead of an html page for display in the browser. Obvious perhaps. But it wasn’t to me at first.
Hello Brennan Young,
Sorry i didn’t get your point?
ScriptManager.RegisterStartupScript(Me, [GetType](), “Javascript”, “javascript:Sch3Collapse(); “, True)
does not work on postback
Hi Pratik,
The above code worked for me, that is I able to call javascript function whenever I clicked asp.net button control. Am not sure how you used above code. But if you have added update panel from ajax toolkit, then you need to add below script at the bottom of your Web page ( .aspx page)
Thank you Sir…. It worked for me perfectly….
Thanks! Works perfectly
Hi John
Am glad this helps you
Thank you.
??how to pass arguments to the javascript function being called.
??returning a result from the javascript function.
Thank you.
Hello Domingo,
For passing arguments / parameters you can simply pass value to the JS function from code-behind C#
For example :
Code behind:
string strParamter = "Hello World test";
ClientScript.RegisterStartupScript(GetType(), "Javascript", "javascript:helloWorld('"+strParamter+"'); ", true);
Client side (.aspx):
function helloWorld(data) {
alert(data);
}
Thanks i was finding it difficult to get javascript function from .cs page .