繁体   English   中英

警报在UpdatePanel中失败

[英]Alert fails in UpdatePanel

我想在Update Panel中的AJAX调用中从服务器获取警报,但是某些原因阻止了HttpContext.Current.Response.Write在客户端上触发。

这是一个非常简单的aspx正文内容

<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <!-- DropDownList doesn't work here -->
        </ContentTemplate>
    </asp:UpdatePanel>
    <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True">
        <asp:ListItem Value="1">First</asp:ListItem>
        <asp:ListItem Value="2">Second</asp:ListItem>
    </asp:DropDownList>
</div>
</form>

这是我在VB中处理它的地方

Protected Sub DropDownList1_SelectedIndexChanged(sender As Object, e As EventArgs) _
        Handles DropDownList1.SelectedIndexChanged
    Dim alertMsg As String
    Dim alertScript As String
    'DO OTHER STUFF HERE
    alertMsg = String.Format("You Selected {0}", DropDownList1.SelectedItem.Text)
    alertScript = String.Format("<script type= text/javascript>alert('{0}');</script>", alertMsg)

    System.Web.HttpContext.Current.Response.Write(alertScript)

End Sub

两次都将触发vb代码,但仅在UpdatePanel外部而不是在内部调用时,才编写警报消息脚本。

我究竟做错了什么?

System.Web.HttpContext.Current.Response.Write在UpdatePanel中不起作用,也许您还遇到了JavaScript错误。

原因是UpdatePanel是在xml结构上准备页面的一部分,并使用ajax将其发送到客户端Response.Write是从另一侧直接尝试在浏览器页面上编写的-但这里我们有ajax调用时,我们没有直接访问页面缓冲区的权限。

要解决您的问题,请在UpdatePanel中使用Literal,然后在该Literal上呈现您的消息-但同样,您无法呈现脚本并希望在更新面板之后运行。

要使脚本在更新面板之后运行,请注册脚本

由于使用的是updatepanel,因此必须使用ClientScriptManager注册脚本。 请尝试以下代码。 它应该工作:

Protected Sub DropDownList1_SelectedIndexChanged(sender As Object, e As EventArgs) _
    Handles DropDownList1.SelectedIndexChanged
    Dim alertMsg As String
    Dim alertScript As String
    'DO OTHER STUFF HERE
    alertMsg = String.Format("You Selected {0}", DropDownList1.SelectedItem.Text)
    alertScript = String.Format("<script type= text/javascript>alert('{0}');</script>", alertMsg)

    'register script on startup
    ClientScriptManager.RegisterStartupScript(Me.[GetType](), "Alert", alertScript);
End Sub

如果我有`

[英]if i have `<asp:UpdatePanel …` than there is no alert message poup

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM