我想从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外部调用时编写警报消息,而不是在其内部。
我做错了什么?
答案 0 :(得分:1)
System.Web.HttpContext.Current.Response.Write
在UpdatePanel内部不起作用,也许你也有javascript错误。
原因是UpdatePanel准备在xml结构中作为页面的一部分,并使用ajax将其发送到客户端 - 来自另一端的Response.Write
直接尝试在浏览器页面上写入 - 但是这里我们有ajax调用,我们没有直接访问页面缓冲区。
要解决您的问题,请在UpdatePanel中使用Literal,并在该Literal上呈现您的消息 - 但同样,您无法呈现脚本并期望在更新面板之后运行。
要在更新面板register your script
之后运行脚本答案 1 :(得分:1)
您必须使用ClientScriptManager注册脚本,因为您使用的是updatepanel。请尝试以下代码。它应该工作:
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