I have the following code on my website:
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel runat="server" id="UpdatePanel" updatemode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger controlid="myButton_btn" eventname="Click" />
</Triggers>
<ContentTemplate>
<script>
function pageLoad(){
window.alert("<%=Session("myVariable")%>");
}
}
</script>
</ContentTemplate>
</asp:UpdatePanel>
<asp:Button ID="myButton_btn" Text="Prev Month" runat="server"></asp:Button>
The javascript is running everytime I c开发者_JAVA百科lick the button. However, even though my subroutine updates the session variable after clicking the button, I always get the same alert. In other words, the same javascript is run after postback, and it is not updated. I am positive that the session variable IS being changed. Does anyone know why this is happening? I appreciate your input!
Thank you so much!
Try this in the button-handler:
VB.Net
ScriptManager.RegisterStartupScript(Me.UpdatePanel, GetType(string), "alertScript", String.Format("alert('{0}');",Session("myVariable")), true)
C#
ScriptManager.RegisterStartupScript(this.UpdatePanel, typeof(string), "alertScript", string.Format("alert('{0}');", Session["myVariable"]), true);
I'm sure there's a better way to do this, but my hack for handling javascript returned within an updatepanel involves registering a function that looks for the new javascript within any UpdatePanels that were updated and then eval()'s their contents. Here's a rough example:
Site.Master:
<script type="text/javascript">
PageLoadedHandler = function(sender, args) {
var panels = args.get_panelsUpdated();
for (var i = 0; i < panels.length; i++) {
var scripts = panels[i].getElementsByTagName('script');
for (var j = 0; j < scripts.length; j++) {
eval(scripts[j].innerHTML);
}
}
}
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(PageLoadedHandler);
</script>
I'm definitely open to cleaner solutions if anyone has one.
精彩评论