Update Javascript after Async Post Back in ASP.NET

2019-05-06 17:49发布

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 click 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!

2条回答
Fickle 薄情
2楼-- · 2019-05-06 18:35

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);
查看更多
SAY GOODBYE
3楼-- · 2019-05-06 18:46

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.

查看更多
登录 后发表回答