Asp. net background calls js 2 methods

  • 2020-09-28 08:50:43
  • OfStack

1. Use Response.Write method

The code is as follows:


Response.Write("<script type='text/javascript'>alert("XXX");</script>");

The drawback of this method is that you cannot call custom functions in the script file, only internal functions are called, and custom functions can only be called with function definitions in Response.Write, for example

Response.Write("<script type='text/javascript'>function myfun(){}</script>");

2. Use ClientScript class

Here's the code: Add the code where you want to call an javascript script function, making sure that MyFun is already defined in the script file.


ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script>MyFun();</script>");

This method is a little more convenient than Response.Write. You can call custom functions in the script file directly.

3. Add the Attributes property of the control

Button1. Attributes. Add("onclick","MyFun();" );

It can only be added in Onload or during initialization like onload. The script function is executed first, and the execution order cannot be changed.

Note that in all of the above methods, the background code cannot have the code to convert the current page, such as Redirect, etc., so put the page-turning code in the script


Related articles: