Call Javascript function from code behind C#: This article explains on button click how to call javascript function in C# . While developing web application there is a common need to call javascript function, based on some logic to do some further business logic . In Asp.net calling JavaScript function from code-behind C# after button click [server-side] is a quite easy code.
About JavaScript function:
JavaScript function is a set of code inside a block, which gets execute on client side. To defined JavaScript function we use the function keyword, followed by a name, and then followed by parentheses ().
Now first, we add an Asp.net Webform in our project and write a JavaScript function. Here default.aspx is our newly added Web page add a javascript function on default.aspx page under head tag, as later we want to call this JS function from code behind. Our simple javascript alert method function look like as written below. We call this alert method from c# codebehind.
<script type="text/javascript" language="javascript">
function helloWorld(){
alert("welcome to codepedia.info");
}
</script>
Two ways to call JavaScript function in C#
- Using ClientScript.RegisterStartupScript
- Using ScriptManager.RegisterStartupScript ( If updatepanel is used)
Method 1: Use ClientScript.RegisterStartupScript to call javascript from code-behind 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 shown below.
//*
ClientScript.RegisterStartupScript(GetType(), "Javascript", "javascript:helloWorld(); ", true);
//*
Method 2: Use ScriptManager.RegisterStartupScript to call javascript from code-behind. If you have used Asp.net UpdatePanel control from ajax toolkit in your web page then the code for calling javascript function would be like as written below.
//*
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: Here in this article we learn how in Asp.net C# using ClientScript.RegisterStartupScript or ScriptManager.RegisterStartupScript we can call any JavaScript function in C# from code-behind may be on page load or on button click.
Other Refernece:
Thank you for reading, pls keep visiting this blog and share this in your network. Also, I would love to hear your opinions down in the comments.
PS: If you found this content valuable and want to thank me? 👳 Buy Me a Coffee
Post Comment
Your email address will not be published. Required fields are marked *