The JavaScript confirm() function is simple to implement on a Button control, but you can only use it for one particular purpose and that is to confirm a postback. Let’s look at an example of this simplicity first and then improve it afterwards. Below is a Button control with an onclick attribute, that opens the confirm dialog. If the user presses the OK button, it will continue with the postback, and if Cancel is pushed nothing will happen.

<asp:Button Runat="server" ID="btnConfirm" Text="Confirm" OnClientClick="return confirm('Are you sure you want to click the button?');" />

confirm box

This is great for scenarios, where you need the user to confirm an action. So, by using this approach you can either continue to make a postback or you can cancel and not make a postback. Wouldn’t it be cool if you could use it to ask users a question and act depending on their answer from the code-behind?

Let’s say you have a web form with a save button and you would like to ask the user whether or not to send the changes by email to the user after it has been saved. Then, depending on the answer given by the user, you would save the changes and send the email. The confirm trick could not do that, because it would simply not postback if the user pressed the Cancel button and thereby not saving anything at all.

Extending the Button control

What we want is a way to always make the postback and at the same time, know what the user answered to the confirm box. That is not possible unless we extend the Button control and adds an Answer property that hold the information of which button was pushed by the user. An answer can only be OK or Cancel, but let’s call them Yes and No and put them in an enumerator.

The Answer enumerator:

/// <summary>
/// The answers from the confirm box.
/// </summary>
public enum Answer
{
   None, // Not answered yet
   Yes,  // OK button
   No    // Cancel button
}

We create the ConfirmButton class and derive from the System.Web.UI.WebControls.Button class:

public class ConfirmButton : Button, IPostBackEventHandler

The Answer property of our new ConfirmButton class:

/// <summary>
/// The answer recieved from the confirm box.
/// </summary>
public Answer Answer
{
   get { return (Answer)(ViewState["Answer"] ?? Answer.None); }
   private set { ViewState["Answer"] = value; }
}

Let’s add another string property called Question that we use as the text in the confirm box.

/// <summary>
/// The question to ask in the confirm box.
/// </summary>
public string Question
{
   get { return (string)(ViewState["Question"] ?? string.Empty); }
   set { ViewState["Question"] = value; }
}

We then have to override the Render method for our new ConfirmButton control. That’s because we now have to pass the confirm dialog answer to the postback JavaScript that resides in the onclick attribute of the control.

protected override void Render(HtmlTextWriter writer)
{
   StringBuilder sb = new StringBuilder();
   foreach (string key in this.Attributes.Keys)
   {
      if (key.ToLowerInvariant() != "onclick")
         sb.Append(key + "=\"" + this.Attributes[key] + "\" ");
   }

   string script = OnClientClick + ";var answer='No'; if (confirm('" + Question.Replace("'", "\\'") + "')){answer='Yes'}";
   string onclick = "onclick=\"" + script + ";__doPostBack('" + this.UniqueID + "', answer)" + "\"";
   string output = string.Format("<input type=\"button\" {0}name=\"" + this.UniqueID + "\" id=\"{1}\" value=\"{2}\" {3} />", sb.ToString(), UniqueID, Text, onclick);

   writer.Write(output);
}

The last thing that needs to be done is to implement the IPostBackEventHandler interface. This enable us to catch the answer passed by the postback JavaScript call and add it to the Answer property of our ConfirmButton class.

void IPostBackEventHandler.RaisePostBackEvent(string eventArgument)
{
   this.Answer = (Answer)Enum.Parse(typeof(Answer), eventArgument);
   base.OnClick(EventArgs.Empty);
}

That’s it. We created a class derived from the Button class, added some methods and properties and now we have our ConfirmButton class.

Implement it the easy way

Download the entire class below and add ConfirmButton.cs to the App_Code folder and then add the following XML to the web.config’s <system.web> section:

<pages>
   <controls>
      <add namespace="CustomControls" tagPrefix="cc" />
   </controls>
</pages>

When you add the namespace of you’re custom controls to the web.config like this, you don’t have to register the controls on every page they are used.

Example of use

Add a Confirmbutton to your page. Notice the Question property:

<cc:ConfirmButton runat="Server" ID="btnSave" OnClick="btnSave_Click" Text="Save" Question="Do you want to recieve an e-mail with the changes?" />

Then add the ConfirmButton.Click event handler and write logic that makes use of the Answer property:

protected void btnSave_Click(object sender, EventArgs e)
{
   SaveForm();

   if (btnSave.Answer == Answer.Yes)
   {
      SendEmail();
   }
}

I believe it to be a very simple control to use by just about anybody, because it behaves just like a regular Button with all the events, properties and method that we are familiar with. It just adds the Question and Answer properties.

Download the ConfirmButton class


ConfirmButton.zip (1,06 KB)

In highly interactive websites and intranet sites, you probably want to let the users know what’s going on when they delete, save, export etc. on the site. Those kinds of status messages are widely used and are often implemented by a JavaScript alert box on the web page. ASP.NET doesn’t natively support JavaScript functions from the code-behind files. You manually have to print out a script tag and add the alert() call to it.

As easy as it may be, the extensive use of the alert() status message though out a website calls for a unified and simple implementation in order to avoid duplicate code – a centralized method.

In Windows Forms it is very easy to pop up a status message by calling MessageBox.Show(“message”). It is that kind of object model we want in ASP.NET for printing out JavaScript alerts. We want Alert.Show(“message”) in ASP.NET.

Such a thing doesn’t exist so we have to create it our selves.

I’ve written a static class called Alert with one public method called Show. The implementation is as simple as can be. Just put the .cs file in the App_Code folder on your website and you instantly have access to the method from all pages and user controls.

using System.Web;
using System.Text;
using System.Web.UI;

/// <summary>
/// A JavaScript alert
/// </summary>
public static class Alert
{

/// <summary>
/// Shows a client-side JavaScript alert in the browser.
/// </summary>
/// <param name="message">The message to appear in the alert.</param>
public static void Show(string message)
{
   // Cleans the message to allow single quotation marks
   string cleanMessage = message.Replace("'", "\\'");
   string script = "<script type=\"text/javascript\">alert('" + cleanMessage + "');</script>";

   // Gets the executing web page
   Page page = HttpContext.Current.CurrentHandler as Page;

   // Checks if the handler is a Page and that the script isn't allready on the Page
   if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert"))
   {
      page.ClientScript.RegisterClientScriptBlock(typeof(Alert), "alert", script);
   }
}    
}

Demonstration

That class of only 30 lines of code enables us to add a JavaScript alert to any page at any time. Here is an example of a Button.Click event handler that uses the method for displaying status messages.

void btnSave_Click(object sender, EventArgs e)
{
   try
   {
      SaveSomething();
      Alert.Show("You document has been saved");
   }
   catch (ReadOnlyException)
   {
      Alert.Show("You do not have write permission to this file");
   }
}

If something was saved without problems, this JavaScript alert box will apear to the user of the website:

Download

Alert.zip (0,57 KB)