UpdatePanel PostBack时执行Javascript范例
之前写过一篇介绍在UpdatePanel动态更新时触发Javascript的方法,不过有网友反应不清楚实作的细节,索性就写一个极简单的程式,实际示范一下。
<%@ Page Language="C#" AutoEventWireup="true" %>
<html>
<head><title>UpdatePanel Call Javascript</title></head>
<body>
<form id="form1" runat="server">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:Button ID="Button1" runat="server" Text="Button"
onclick="Button1_Click" />
<asp:HiddenField ID="hdnScript" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(blah);
function blah() {
eval($get("hdnScript").value);
}
</script>
</form>
<script type="text/C#" runat="server">
protected void Button1_Click(object sender, EventArgs e)
{
hdnScript.Value = "alert(''I did it!'');";
}
</script>
</body>
</html>运作的原理是利用add_endRequest()在每次UpdatePanel Postback时触发blah()函数,blah()会用eval()执行Hidden栏位的字串值,所以在Server-Side将要执行的Javascript Code以字串方式传回,按下按钮后就会被执行。 That''s all, folks.
PS: 顺便宣导一下资安观念,传回的Javascript Code不宜开放给User自行输入或更动,不然会造成XSS攻击的漏洞。
PS2: 用VS 2008写这段Code时,输入Sys.WebForms.PageRequestManager.getInstance()后还会提示add_Request,不亦快哉!!
Javascript牛人Ammon再露了一手,提供更简便的做法ScriptManager.RegisterStartupScript(),在此谢过:
<%@ Page Language="C#" AutoEventWireup="true" %>
<html>
<head><title>UpdatePanel Call Javascript</title></head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Button ID="Button1" runat="server" Text="Button"
onclick="Button1_Click" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
<script type="text/C#" runat="server">
protected void Button1_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(Button1, typeof(Button),
"alert", "alert(''Amazing'');", true);
}
</script>
</body>
</html>