0

我正在从 asp.net(vb) 中的代码隐藏生成一个 javascript 警报框。

编码:

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

消息框功能如下:

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 的 form 标记中:

        <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)中?

4

3 回答 3

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

Using JavaScriptSerializer should take care of the linebreaks, single quotes, and everything else we haven't already thought of.

于 2012-06-30T13:19:05.570 回答
1

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

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

于 2012-06-30T12:48:52.097 回答
1

要继续 Pointy 给出的答案,您的消息包含'您需要转义的字符。

试试这个...

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

type='text/javascript'拥有而不是language='javascript'......虽然这不是绝对必要的,但它也更好。

于 2012-06-30T13:12:41.977 回答