Note to cautious readers ...
There are two quite serious problems with the above-describedPromptButton
implementation.
Take a look at the code once again. Can you spot the problems?
Here are some hints...
PromptButton.ConfirmMessage = Nothing
PromptButton.ConfirmMessage = "What's up?"
Nothing
to the
ConfirmMessage
property (in the
Page_Load
event, for example),
System.NullReferenceException
will be thrown in the
PromptButton.AddAttributesToRender
method.
The second one, however, is more dangerous, because it doesn't manifest so "loudly". That is, when the ConfirmMessage
string contains an apostrophe, the generated client-side script will be invalid and no confirmation prompt will be displayed on the client at all!
Fortunately, the cure is easy - here is a more robust implementation of the PromptButton
class (the additions are marked with bold text): Would you say that a few simple lines of the PromptButton
code could break the whole application?
Imports System.ComponentModel
Imports System.Web.UI.WebControls
<ToolboxData("<{0}:PromptButton runat=""server"" ConfirmMessage=""Hello!"" />")> _
Public Class PromptButton
Inherits Button
Private _ConfirmMessage As String = String.Empty
' Our confirmation message or String.Empty if no
' confirmation prompt should be displayed on the client.
Public Overridable Property ConfirmMessage() As String
Get
Return _ConfirmMessage
End Get
Set(ByVal Value As String)
_ConfirmMessage = Value
' Test for Nothing on this one place, instead of
' here and there throughout the implementation.
If _ConfirmMessage Is Nothing Then
_ConfirmMessage = String.Empty
End If
End Set
End Property
Protected Overrides Sub AddAttributesToRender( _
ByVal writer As System.Web.UI.HtmlTextWriter)
If _ConfirmMessage.Length > 0 Then
' Change embedded apostrophes to corresponding
' escape sequences.
Dim EscapedMessage As String = Replace(_ConfirmMessage, "'", "\'")
writer.AddAttribute("onclick", _
"return confirm('" & EscapedMessage & "');")
End If
MyBase.AddAttributesToRender(writer)
End Sub
End Class
Comments