Javascript alert not working from code behind

后端 未结 3 1687
闹比i
闹比i 2021-01-28 11:29

I am generating a javascript alert box from codebehind in asp.net(vb).

The code:

            Catch ex As Exception
                MesgBox(\"Error in up         


        
相关标签:
3条回答
  • 2021-01-28 11:50

    JavaScript does not allow string constants to span line breaks.

    In your server-side code, you're going to have to replace the newlines in the error message with "\n".

    0 讨论(0)
  • 2021-01-28 11:53

    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
    

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

    0 讨论(0)
  • 2021-01-28 12:06

    To carry on with the answer given by Pointy, your message contains ' characters, which you need to escape.

    Try this...

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

    It is also better to have type='text/javascript' rather than language='javascript'... although this is not absolutely necessary.

    0 讨论(0)
提交回复
热议问题