问题:
<asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <%= DateTime.Now.ToString()%><br /> <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label><br /> <asp:Button ID="Button2" runat="server" Text="Button" /> <script > alert("Hellow World!"); </script> </ContentTemplate> </asp:UpdatePanel>
首次加载,alert会执行,点击Button2时间更新,脚本不在执行。
解决方案:
1.在App_Code中新建一个类,继承Control.
namespace Demo{ public class InlineScript : Control { protected override void Render(HtmlTextWriter writer) { //通过ScriptManager判断是异步刷新,还是首次加载 ScriptManager sm = ScriptManager.GetCurrent(this.Page); if (sm.IsInAsyncPostBack) { //异步刷新 System.Text.StringBuilder sb = new System.Text.StringBuilder(); base.Render(new HtmlTextWriter(new System.IO.StringWriter(sb))); ScriptManager.RegisterStartupScript(this, typeof(InlineScript), this.UniqueID, sb.ToString(), false); } else { base.Render(writer); } } } }
2.在UpdatePanel所在页面注册该 tag。
<%@ Register Namespace="Demo" TagPrefix="Demo" %>
3.把UpdatePanel中的javascrip脚本用 <Demo:InlineScript>包围住。
<Demo:InlineScript runat="server"> <script > alert("Hellow World!"); </script> </Demo:InlineScript>