Intermodulation of ASP.NET and JavaScript functions
ASP.NET allows front-end and back-end codes (CodeBehind and JavaScript) to call each other's functions to achieve dynamic interaction.
Calling JavaScript from CodeBehind
To call JavaScript functions in CodeBehind, you can use ClientScriptManager
. This manager provides methods to register and run JavaScript.
For example, to call a JavaScript function named MyFunction
when the page loads, you would use the following code:
<code class="language-csharp">Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "MyFunction()", true);</code>
This code registers the MyFunction
call as a startup script to be executed when the page loads.
Call CodeBehind from JavaScript
To call CodeBehind from JavaScript, you can use the PageMethods
class. This class provides a way to expose server-side methods to JavaScript.
For example, to call the CodeBehind method named HelloWorld
, you can use the following JavaScript code:
<code class="language-javascript">PageMethods.HelloWorld(function(result) { // 处理结果 });</code>
This code calls the HelloWorld
method, passing a callback function that will be called after the server-side method completes.
Application scenario examples
Client-side verification is a common scenario that requires CodeBehind and JavaScript to call each other:
The above is the detailed content of How to Call JavaScript Functions from ASP.NET CodeBehind and Vice Versa?. For more information, please follow other related articles on the PHP Chinese website!