Unable to trigger JavaScript method from code-behi

2019-07-29 12:40发布

问题:

Issue details:

After saving the data in DB, I need to show an alert to the user. For this, I have registered the script from code-behind. But it is NOT working with update-panel whereas it works as expected without update-panel. I need to make it work with update-panel.

I tried by adding $(document).ready(function () while registering the script, but it didn't work.

Then, I tried with ScriptManager.RegisterClientScriptBlock() method instead of Page.ClientScript.RegisterStartupScript(), but it also didn't work.

Here is the code snippet of web page (ASPX):

<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
        <asp:Button ID="btnOutsideUpdatePanel" runat="server" Text="Outside UpdatePanel" OnClick="btnOutsideUpdatePanel_Click" />
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <asp:Button ID="btnInsideUpdatePanel" runat="server" Text="Inside UpdatePanel" OnClick="btnInsideUpdatePanel_Click" />
            </ContentTemplate>
        </asp:UpdatePanel>
        <uc1:Child runat="server" id="Child1" />
         <asp:UpdatePanel ID="UpdatePanel2" runat="server">
            <ContentTemplate>
                <uc1:Child runat="server" id="Child2" />
            </ContentTemplate>
        </asp:UpdatePanel>
    </form>
</body>

Here is the code snippet of user-control (ASCX):

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Child.ascx.cs" Inherits="UpdatePanelAndScript.Child" %>
<asp:Button ID="btnUserControl" runat="server" Text="User Control" OnClick="btnUserControl_Click" />

Code-behind of web-page:

protected void btnOutsideUpdatePanel_Click(object sender, EventArgs e)
{
    Page.ClientScript.RegisterStartupScript(this.GetType(), "ShowSuccess", "alert('Hi');", true);
}

protected void btnInsideUpdatePanel_Click(object sender, EventArgs e)
{
    Page.ClientScript.RegisterStartupScript(this.GetType(), "ShowSuccess", "alert('Hi');", true);
}

Code-behind of user-control:

protected void btnUserControl_Click(object sender, EventArgs e)
{
    Page.ClientScript.RegisterStartupScript(this.GetType(), "ShowSuccess", "alert('Hi');", true);
}

回答1:

You only need to change the following statement:

Page.ClientScript.RegisterStartupScript
(
    this.GetType(),
    "ShowSuccess",
    "alert('Hi');",
    true
);

To:

ScriptManager.RegisterStartupScript
(
    this,
    this.GetType(),
    "ShowSuccess",
    "alert('Hi');",
    true
);

Reference:

  • MSDN ScriptManager Class

Registering Partial-Page Update Compatible Scripts
[...] If you are rendering script for use inside an UpdatePanel control, make sure that you call the methods of the ScriptManager control.