How do I call a JavaScript function from Asp.Net code?

This is my JavaScript function:

function WantToSave()
{
    alert('You should save now !');
}

And this is my ASP.NET code:

Page.ClientScript.RegisterStartupScript(this.GetType(), "MyKey", "WantToSave();");

The function is being executed RegisterStartupScript. But this will not call my JavaScript function. And this second parameter, it should be the "Script Launch Key" yes, but what should I put there?

+4
source share
4 answers

By default, the script writes to the output, but without tags <script>. You would probably notice this if you use the browser JavaScript console or view the resulting HTML on the client. Be sure to check out these tools.

script .

Page.ClientScript.RegisterStartupScript(this.GetType(), "MyKey", "WantToSave();", true);

:

Page.ClientScript.RegisterStartupScript(this.GetType(), "MyKey", "<script>WantToSave();</script>");

, , script, script. , - , - .

+5

script script. bool (), add script , script .

ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "WantToSave();",true); 
+2

:

var name = "WantToSave";
var script = "<script>alert('You should save now !');</script>";
Page.ClientScript.RegisterStartupScript(this.GetType(), name, script);

, script.

Page.ClientScript.RegisterStartupScript(this.GetType(), "MyKey", "WantToSave();",true);
+1
source

According to the MSDN using this overload, you have to wrap your call in tags <script></script>so that you do:

Page.ClientScript.RegisterStartupScript(this.GetType(), "MyKey", "<script>WantToSave();</script>");

or use another overload

Page.ClientScript.RegisterStartupScript(this.GetType(), "MyKey", "WantToSave();", true);

which will add them or is not dependent on a logical parameter.

0
source

Source: https://habr.com/ru/post/1606789/


All Articles