2012-02-08 65 views
1

我使用下面的代码btnClick事件中:无法注册启动脚本

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

脚本被注册的<body>内,我没有得到任何警告。

如何注册启动脚本并获取此警报消息?如果要执行上按一下按钮脚本则不要使用ClientScript.RegisterStartupScript()

我会建议你使用ClientScript.RegisterClientScriptBlock()

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

您是否尝试在函数调用中添加括号?例如,而不是“exampleScript”,请尝试“exampleScript()”。 – 2012-02-08 16:53:18

+0

这就是“脚本键”,而不是函数名。它只是使用该密钥将脚本注册到registerstartupscript – 2012-02-08 16:54:51

+1

您是否尝试从更新面板中注册启动脚本? – 2012-02-08 16:58:07

回答

5

您是否使用AJAX?

因此,无论您的页面上有ScriptManager实例,都需要使用ScriptManager注册脚本。所以,你需要改变这样的

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

谢谢。我在做一个没有任何Ajax的示例应用程序。您的解决方案完美工作 – Ananth 2012-02-08 17:32:57

1

试试这个事件

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()事件,如果你想在页面上用按钮来注册脚本加载

1

,而不是它重视的JavaScript和按钮客户端点击:

2

的问题是,你需要在活动期间调用ClientScript.RegisterStartupScriptPage_Load(),不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

+0

+1在答案开始时的解释 – Devjosh 2012-02-08 17:06:58

1

我相信答案已经给出,所以让我解释一下什么选择你在ASP.NET中有。

ASP.NET提供了两种将JavaScript资源添加到页面的方法。

  1. ClientScriptManager(经由Page.ClientScript访问)

  2. 的ScriptManager和的ScriptManagerProxy

第二选项支持更多或更少的相同,第一,但也为ASP.NET支持AJAX和WebService &脚本引用。如果你不使用任何这些额外的东西,那么通常我会选择第一个选项。

目前尚不清楚您使用的是什么,但如果您使用更新面板,则必须使用第二个选项。