问题描述
我生成从codebehind在asp.net(VB)一个JavaScript警告框。
I am generating a javascript alert box from codebehind in asp.net(vb).
在code:
Catch ex As Exception
MesgBox("Error in uploading file due to following exception" & vbNewLine & ex.ToString)
trans.Rollback()
Finally
conn.Close()
End Try
的mesgbox功能如下:
The mesgbox function is as follows:
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表单标签附加:
Now when exception is thrown, the following script is appended in the form tag of the client side 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)?
Why is this not appearing in my browser(Firefox)?
推荐答案
添加进口System.Web.Script.Serialization
到文件的顶部,那么试试这个:
Add Imports System.Web.Script.Serialization
to the top of your file, then try this:
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应该照顾的换行符的,单引号,和其他一切,我们还没有想到的。
Using JavaScriptSerializer should take care of the linebreaks, single quotes, and everything else we haven't already thought of.
这篇关于JavaScript警告不从code工作背后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!