The confirmation should occur on the client side. This requires that you react
to the client side onclick event handler. Within this function
you can use the Javascript confirm function to display a confirmation
message to the user. It displays a simple message with OK and Cancel buttons.
It returns true if the user clicks OK or false if the user clicks Cancel.
Returning false from the handler will cancel the click event. To attach this
to an ASP.NET control you have to add a new attribute to the control with the Javascript
code as the value. The Attributes collection exposed by server
controls allows you to add arbitrary HTML attributes to a control. They will
be rendered at runtime. To add a confirmation message to a button you would
use the following code.
Attributes.Add("onclick", "return confirm('Are you sure?');");
A few notes about the above code. First notice the mixing of single and double
quotes. This is necessary because you can not nest quotes within quotes.
Single quotes identify strings in HTML as well. Secondly notice a call to
return. Since this is being done, and since it is a button,
we do not need to deal with the event object at all. Finally
notice that the attribute value is actually Javascript code. We can technically
call any Javascript function we want here but it is best to keep it simple.
Using the above code as a baseline we can build a simple server control to encapsulate this.
public class ConfirmButton : Button
{
public string ConfirmMessage
{
get
{
object obj = ViewState["ConfirmMessage"];
return (obj != null) ? (string)obj : "Are you
sure?";
}
set
{
value = (value != null) ? value.Trim() : "";
if (value.Length > 0)
ViewState["ConfirmMessage"] = value;
else
ViewState.Remove("ConfirmMessage");
}
}
protected override void OnPreRender ( EventArgs e )
{
base.OnPreRender(e);
if ((ConfirmMessage.Length > 0) && (Page != null))
Attributes.Add("onclick", "return confirm('" +
Page.Server.HtmlEncode(ConfirmMessage) + "');");
}
}
A slightly different version of this code is available in an upcoming release of Kraken.
Notice the call to Page.Server.HtmlEncode. This ensures that
someone can not create a malformed HTML string in the page.