无法注册启动脚本

Unable to register startup script

本文关键字:脚本 启动 注册      更新时间:2023-09-26

我在btn Click事件中使用以下代码:

 ClientScript.RegisterStartupScript(typeof(Page), "exampleScript", "alert('you just registered the start up script');", true);

脚本在<body>中注册,我没有收到任何警报。

注册启动脚本并获取此警报消息的方法是什么?

您在使用AJAX吗?

因此,每当页面上有ScriptManager实例时,都需要使用ScriptManager注册脚本。所以你需要像这个一样更改代码

ScriptManager.RegisterStartupScript(this, this.GetType(), "exampleScript", "alert('Hello');", true);

问题是在类似Page_Load()的事件期间需要调用ClientScript.RegisterStartupScript,而不是Button_Click。

这样,要执行代码,您需要对代码进行客户端Javascript调用

Page_Load()
{
    ClientScript.RegisterStartupScript(typeof(Page), "exampleScript", "yourFunc();", true);
}
<asp:Button OnClientClick = "yourFunc()" .....

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.onclientclick.aspx

试试这个:

ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "myKey", "alert('you just registered the start up script');", true);

我相信答案已经给出了,所以让我解释一下您在ASP.NET中有哪些选项。

ASP.NET提供了两种将JavaScript资源包含到页面中的方法。

  1. ClientScriptManager(可通过Page.ClientScript访问)

  2. ScriptManager和ScriptManagerProxy

第二个选项支持与第一个选项大致相同的功能,但也支持ASP.NET AJAX和WebService&脚本引用。如果你不使用任何额外的,那么通常我会选择第一个选项。

目前还不清楚你到底在使用什么,但如果你使用更新面板,那么你就必须使用第二个选项。

如果您想在按钮上执行脚本,请单击,然后不要使用ClientScript.RegisterStartupScript()

我建议你使用ClientScript.RegisterClientScriptBlock(),而不是它附加了带有按钮客户端点击事件的JavaScript

ClientScript.RegisterClientScriptBlock(Page, typeof(Page),alert(' i am executed on button click'), true);

请参阅此

如果您想在每次页面加载时执行脚本,请使用ClientScript.RegisterStartupScript()

您还可以选择使用以下方法
btn.Attributes.Add("onclick","<script>alert('hello alert')</script>");在Page_Load()事件中,如果您希望使用页面上的按钮注册脚本,请加载