我在btn
Click
事件中使用以下代码:
ClientScript.RegisterStartupScript(typeof(Page), "exampleScript", "alert('you just registered the start up script');", true);
脚本在<body>
内注册,我没有收到任何警报。
注册启动脚本并获取此警报消息的方法是什么?
答案 0 :(得分:5)
您使用的是AJAX吗?
因此,只要您的页面上有ScriptManager实例,就需要使用ScriptManager注册脚本。所以你需要像这样改变代码
ScriptManager.RegisterStartupScript(this, this.GetType(), "exampleScript", "alert('Hello');", true);
答案 1 :(得分:2)
问题是您需要在ClientScript.RegisterStartupScript
之类的活动中致电Page_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
答案 2 :(得分:1)
试试这个:
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "myKey", "alert('you just registered the start up script');", true);
答案 3 :(得分:1)
如果要在按钮上单击执行脚本,请不要使用ClientScript.RegisterStartupScript()
我建议您使用ClientScript.RegisterClientScriptBlock()
,而不是使用按钮客户端点击事件附加JavaScript
ClientScript.RegisterClientScriptBlock(Page, typeof(Page),alert(' i am executed on button click'), true);
参考this
如果您想在每次加载页面时执行脚本,请使用ClientScript.RegisterStartupScript()
您也可以选择使用以下方法
btn.Attributes.Add("onclick","<script>alert('hello alert')</script>");
如果您希望使用页面加载
答案 4 :(得分:1)
我相信已经给出了答案,所以让我解释一下你在ASP.NET中有哪些选项。
ASP.NET提供了两种将JavaScript资源包含到页面中的方法。
ClientScriptManager(可通过Page.ClientScript访问)
ScriptManager和ScriptManagerProxy
第二个选项支持或多或少与第一个选项相同,但也支持ASP.NET AJAX和WebService&amp;脚本参考。如果你不使用任何额外的,那么我通常会选择第一个选项。
目前尚不清楚你究竟使用的是什么但是如果使用更新面板则必须使用第二个选项。