Javascript警报无法从代码背后工作

时间:2012-06-30 12:46:19

标签: javascript asp.net vb.net

我正在asp.net(vb)中从codebehind生成一个javascript警告框。

代码:

            Catch ex As Exception
                MesgBox("Error in uploading file due to following exception" & vbNewLine & ex.ToString)
                trans.Rollback()
            Finally
                conn.Close()
            End Try

mesgbox功能如下:

Private Sub MesgBox(ByVal sMessage As String)
    Dim msgedtble As String = sMessage.Replace("\", "\\")
    msgedtble = msgedtble.Replace(vbNewLine, "\n")
    Page.ClientScript.RegisterStartupScript(Me.GetType,
 "myScripts",
 "<script language='javascript'>alert('" & msgedtble & "');</script>")

End Sub

现在抛出异常时,以下脚本会附加在客户端html的表单标记中:

        <script language='javascript'>alert('Error in uploading file due to following exception\nSystem.Data.SqlClient.SqlException (0x80131904): Violation of UNIQUE KEY constraint 'IX_AccountMaster'. Cannot insert duplicate key in object 'dbo.AccountMaster'.\nThe statement has been terminated.\n   at System.Data.Common.DbDataAdapter.UpdatedRowStatusErrors(RowUpdatedEventArgs rowUpdatedEvent, BatchCommandInfo[] batchCommands, Int32 commandCount)\n   at System.Data.Common.DbDataAdapter.UpdatedRowStatus(RowUpdatedEventArgs rowUpdatedEvent, BatchCommandInfo[] batchCommands, Int32 commandCount)\n   at System.Data.Common.DbDataAdapter.Update(DataRow[] dataRows, DataTableMapping tableMapping)\n   at System.Data.Common.DbDataAdapter.UpdateFromDataTable(DataTable dataTable, DataTableMapping tableMapping)\n   at System.Data.Common.DbDataAdapter.Update(DataTable dataTable)\n   at UploadAccountMasterXl.Button1_Click(Object sender, EventArgs e) in C:\\Users\\ssaa\\Documents\\Visual Studio 2010\\WebSites\\Dpp2012\\UploadAccountMasterXl.aspx.vb:line 57');</script>

为什么这不会出现在我的浏览器(Firefox)中?

3 个答案:

答案 0 :(得分:2)

Imports System.Web.Script.Serialization添加到文件顶部,然后尝试:

Private Sub MesgBox(ByVal sMessage As String)
    Dim serializer as New JavaScriptSerializer()
    Dim msgedtble As String = serializer.Serialize(sMessage)
    Page.ClientScript.RegisterStartupScript(Me.GetType, "myScripts",
        "<script type='text/javascript'>alert(" & msgedtble & ");</script>")
End Sub

使用JavaScriptSerializer应该处理换行符,单引号以及我们尚未想到的所有其他内容。

答案 1 :(得分:1)

JavaScript不允许字符串常量跨越换行符。

在服务器端代码中,您将不得不用“\ n”替换错误消息中的换行符。

答案 2 :(得分:1)

要继续Pointy给出的答案,您的邮件中包含'个字符,您需要将其转义。

试试这个......

  msgedtble = msgedtble.Replace(vbNewLine, "\n").Replace("'","\'")

最好是type='text/javascript'而不是language='javascript' ...虽然这不是绝对必要的。