问题
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