Update Javascript after Async Post Back in ASP.NET

ε祈祈猫儿з 提交于 2019-12-07 10:20:23

问题


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!


回答1:


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);



回答2:


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.



来源:https://stackoverflow.com/questions/4900522/update-javascript-after-async-post-back-in-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!