ASP.NET server side show JS Alert box, doesn't work when using partial post back

我们两清 提交于 2019-12-11 14:55:21

问题


I have put the following method in my master page. It works when I call it on a full post back, but when I call it from a updatePanel's asyncPostBack no alert is shown.

    public void ShowAlertMessage(String message)
    {
        string alertScript = 
            String.Format("alert('{0}');", message);
        Page.ClientScript.RegisterStartupScript(this.GetType(), "Key", alertScript, true);
    }

What do I need to do so it works on partial post backs?


回答1:


You have to register the script with the ScriptManager:

ScriptManager.RegisterStartupScript(this, typeof(Page), UniqueID, "alert('hi')", true);

Here is some more information:

Inline Script inside an ASP.NET AJAX UpdatePanel




回答2:


You should use ScriptManager.RegisterStartupScript instead:

<%@ Page Language="C#" AutoEventWireup="true" %>
<script runat="server" type="text/C#">
protected void BtnClick(object sender, EventArgs e)
{
    string alertScript = "alert('Hello');";
    ScriptManager.RegisterStartupScript(this, GetType(), "Key", alertScript, true);
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="sm" runat="server" />
    <asp:UpdatePanel ID="up" runat="server">
        <ContentTemplate></ContentTemplate>
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="btn" EventName="Click" />
        </Triggers>
    </asp:UpdatePanel>
    <asp:LinkButton ID="btn" runat="server" OnClick="BtnClick" Text="Test" />
    </form>
</body>
</html>


来源:https://stackoverflow.com/questions/2510346/asp-net-server-side-show-js-alert-box-doesnt-work-when-using-partial-post-back

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