Unfortunally aspnet hasn't a builtin control and we have to play a bit to achieve our goal.
Today i'll explain a simple way to use it, tested on framework 2.0 and 3.5 (insde updatepanels) (3.5 has a builtin msgBox but it has some problems once we publish the application, but i'll discuss this later).
A good way to go is to build up an Utility Class and make shared most of the methods we construct inside it. Doing this we dont have to initialize the class everytime to call a method.
Here we go:
Public Shared Sub AlertScript(ByVal myPage As System.Web.UI.Page, ByVal sMessage As String)
Dim chiave As String = "alert('" + JavaEncode(sMessage) + "')"
Dim MyKey As String = "chiave"
System.Web.UI.ScriptManager.RegisterClientScriptBlock(myPage, myPage.GetType, MyKey, chiave, True)
End Sub
and let's assume we put this inside our Utility Class called CLSUtility
Now from our page we just have to call the method AlertScript in this way :
CLSUtility.AlertScript(me,"Your Message Here")
JAVAENCODE FUNCTION
Function JavaEncode(ByVal strResponse As String) As String
Dim strVal As String
'
If Not strResponse Is Nothing Then
strVal = strResponse
' Carattere \
strVal = Replace(strVal, "\", "\\")
' Carattere '
strVal = Replace(strVal, "'", "\'")
' Carattere &
strVal = Replace(strVal, "&", "\&")
' Carattere %
strVal = Replace(strVal, "%", "\%")
' Carattere "
strVal = Replace(strVal, """", "\""")
' Carattere +
strVal = Replace(strVal, "+", "\+")
' Carattere <
strVal = Replace(strVal, "<", "\<")
' Carattere >
strVal = Replace(strVal, ">", "\>")
' Carattere
strVal = Replace(strVal, Chr(10), "\r")
strVal = Replace(strVal, Chr(13), "")
strVal = Replace(strVal, """", "'")
Return strVal
Else
Return Nothing
End If
''
End Function
Here you go, hoping that this little tip may help some of you.
This works also if you put your button or whatever inside an Ajax UpdatePanel
Later i'll post a great control that uses the AjaxToolkit to show up MessageBox with different colors according the priority of the message\error.
Stay tuned.
5 comments:
Error - Javaencode not declared. what to do?
Hey m8, yeah sorry.
It's an homemade function to encode javascript text.
For simple purpose you can remove that function
so "alert('" + JavaEncode(sMessage) + "')" will be "alert('" + sMessage + "')"
I'll publish later the JavaEncode function.It basically check for excape text.
Hi, and thanks.
Can you please provide a JavaEncode code sample?
Thanks
updated the Post with the JavaEncode function.
Cheers
FYI small typo in JavaEncode...
line 19: strValstrVal
Post a Comment