How Do I Add a Client Side Message Box to ASPX Pages?

Update: 06/11/2006
Due to a number of requests I received, I have added a VB version of the code example in this article

In many applications, it's common practice to use a client side dialog, like a message box, to ask the user for confirmation or display a message. For example, if you allow a user to delete, say, an article on your site, you better ask if they are sure they want to delete the item. Many people know they can add a confirmation box to standard HTML or classic ASP pages. However, the same trick is less well known for ASPX pages, but just as possible and easy to implement. This FAQ will show you a few different scenario's for adding a confirmation dialog to your ASPX pages.

Adding a Confirmation Dialog to Standard Buttons

This is probably the most common scenario; you have a simple button that, when clicked, posts the page back to the server where some logic is performed. But before the postback occurs, you want to give your users a way out in case they hit the Delete button by mistake, or because they changed their mind (users do that, you know). There are many situations where this can be used: in a shopping cart on the "Finalize Order" page to ask if the user really wants to order the goods. Or on a forum where you can post a new message. There are really many uses for a dialog box like this.
When you try to add the confirmation dialog, your first attempt may look like this:

  Text="Click Me" 
  OnClick="return confirm('Are you sure you want to do this');">
However, when you run this code, you get a compilation error. Since the button is a server side button, the OnClick is interpreted as a server side instruction, and not as a client side script instruction. The trick is to add the onclick handler at run time through the Attributes collection of the control. In the code below I am adding the attributes in the Page_Load method of the page, but of course you can add this code to other locations in your code as well:

private void Page_Load(object sender, System.EventArgs e)
       "return confirm('Are you sure you want to do this');");
Private Sub Page_Load(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles MyBase.Load
  btnDoSomething.Attributes.Add("onclick", _
        "return confirm('Are you sure you want to do this');")
End Sub

When you compile this code, and run the page the button will now ask for confirmation when it's clicked. When you press OK, the page will be submitted to the server, causing a postback. If you cancel, nothing happens and the page stays as it was. If you look at the resulting HTML in the browser, this is what you'll see:

  value="Click Me" 
  onclick="return confirm('Are you sure you want to do this?');"

This looks remarkably similar to the first code I showed you. However, this time the onclick handler is true client side code, causing the confirmation dialog to pop up on the client. If you press Cancel on the confirmation dialog, false is returned. In the end, this results in the default action for the button (submit back to the server) being ignored.

Displaying a Message Box at Load Time

Another common use for a dialog box is to display a confirmation message when the page loads. Usually, this is done by adding some JavaScript code to the onload of the body tag like this:

<body onload="alert('Hi there');">

This works fine when you need to show the dialog every time the page loads. But what if you want to display the dialog only after a post back? For example, when you want to use a dialog to tell your users their login attempt failed. In such a scenario, you'll need to use RegisterStartupScript. With this method you can add JavaScript of your choice to the page so it fires when the page loads. Instead of using an onload handler for the body tag, the ASP.NET run-time injects your JavaScript to the end of the page, right before the closing </form> and </body> tags. This can lead to a bit messy code, but it'll work almost the same as a cleaner handler. To try it out, add the following code to your page:

if (Page.IsPostBack)
{  Page.RegisterStartupScript("ScriptDescription", 
    "<script type=\"text/javascript\">
    alert('Login Failed. Please try again');</script>");
If Page.IsPostBack Then
  Page.RegisterStartupScript("ScriptDescription", _
        "<script type=""text/javascript"">alert('Login Failed. " & _
        "Please try again');</script>")
End If

(Note that the three lines of code that starts with Page.RegisterStartupScript should be on one line). As you can see, this code only runs when the page has been posted back, for example by clicking a Login button. The ScriptDescription can be any name you choose, as long as it's unique for the current page. When you try to register a script block with the same key, the previous block will be overwritten.
The name for the method that adds the code is a bit misleading as you can "register" any type of text or HTML code and not just script. That's why it's necessary to add the <script> tag yourself; if you omit that, the text will end up as plain text in your page. If you look at the HTML source of the resulting page, this is what you'll see:

        type="text/javascript">alert('Login Failed. Please try again!');

Adding a Confirmation Dialog to a DataGrid

The final example I want to show you is adding a confirmation box to a button in a DataGrid. Because the buttons are created for each item in the datasource you're binding your DataGrid to, you can't access the button directly to add the Attributes, as I showed you in my first example. However, adding the onclick handler to each button in the grid is easier than you might think. Consider the following simple DataGrid:

<asp:DataGrid id=DataGrid1 runat="server" 
     ShowHeader="False" AutoGenerateColumns="False">
        <%# Container.DataItem%>
        <asp:Button ID="MyButton" Runat="server" Text="Delete" />

With the following code, I can easily bind some data to the grid:

private void Page_Load(object sender, System.EventArgs e)
  string[] movies = new string[] {"Reservoir Dogs", 
    "Pulp Fiction", "Natural Born Killers", "12 Monkeys"};
  // Bind the datasource to the DataGrid
  DataGrid1.DataSource = movies;
Private Sub Page_Load(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles MyBase.Load
  Dim movies As String() = New String() {"Reservoir Dogs", _
        "Pulp Fiction", "Natural Born Killers", "12 Monkeys"}
  ' Bind the datasource to the DataGrid
  DataGrid1.DataSource = movies
End Sub

When you run the page, the Delete button will always cause a post back. To add the client side JavaScript dialog that asks for confirmation box you'll need to make a few changes to the code. First of all, you need a method that is called for each item that you add to the DataGrid. Inside that method, you need to get a reference to the button in the item being added, and then add the JavaScript. Finally, you'll need to hook up that method to the control's ItemCreated event. The method should look similar to this:

public void MyItemCreated(object sender, 
      System.Web.UI.WebControls.DataGridItemEventArgs e)
  switch (e.Item.ItemType)
    case ListItemType.Item:
    case ListItemType.AlternatingItem:
      Button myButton = (Button) e.Item.FindControl("MyButton");
         "return confirm('Are you sure you want to delete " 
          + e.Item.DataItem.ToString() + "?');");
    catch {}
Protected Sub MyItemCreated(ByVal sender As Object, _
         ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs)

  Select Case e.Item.ItemType
    Case ListItemType.Item, ListItemType.AlternatingItem
      Dim myButton As Button = CType(e.Item.FindControl("MyButton"), Button)
      myButton.Attributes.Add("onclick", _
                 "return confirm('Are you sure you want to delete " _
                 + e.Item.DataItem.ToString() + "?');")
  End Select
End Sub        

For each item that is added to the DataGrid this method is called. Inside the method I use a switch statement (Select Case in VB.NET) to distinguish between the real data items and other items like the Header and Footer for example. Once I know I have an Item or Alternating item I use the FindControl method to get a reference to the Delete button I defined in my template earlier. Note that FindControl returns a generic Control object. The Control class does not have an Attributes collection, so you'll need to cast it to the appropriate control; a Button in this example.
I also use e.Item.DataItem.ToString() to get a string representation of the DataItem that is being bound. I use this string to customize the confirmation message.

The final step is to link this method to the Grid's ItemCreated event. Modify the <asp:DataGrid code as follows:


Now when you run the page, and click one of the delete buttons, this is what you'll see:

Figure 1: The customized confirmation message.

I leave the actual Delete implementation to you, or to a future article.

ASP.NET 2.0 Makes a Confirmation Dialog a Lot Easier

The Button, LinkButton and Imagebutton controls have an OnClientClick property in ASP.NET 2.0 that makes displaying a confirmation dialog even easier. Just set this property to the confirm code you saw earlier:

<asp:Button ID="Button1" runat="server" Text="Delete" 
    OnClientClick="return confirm('Are you sure 
             you want to delete this item?');" />

You can use this code in a plain button that you place directly on a form, but also with buttons that are part of data bound controls, like the new GridView control.

Download Files

Source Code for This Article (C# Only)

Where to Next?

Wonder where to go next? You can post a comment on this article.

Doc ID 355
Full URL
Short cut
Written by Imar Spaanjaars
Date Posted 02/12/2005 18:47
Date Last Updated 06/11/2006 10:29
Date Last Reviewed 06/11/2006 10:29
Listened to when writing Me & My Friends by Red Hot Chili Peppers (Track 3 from the album: The Uplift Mofo Party Plan)


Talk Back! Comment on Imar.Spaanjaars.Com

I am interested in what you have to say about this article. Feel free to post any comments, remarks or questions you may have about this article. The Talk Back feature is not meant for technical questions that are not directly related to this article. So, a post like "Hey, can you tell me how I can upload files to a MySQL database in PHP?" is likely to be removed. Also spam and unrealistic job offers will be deleted immediately.

When you post a comment, you have to provide your name and the comment. Your e-mail address is optional and you only need to provide it if you want me to contact you. It will not be displayed along with your comment. I got sick and tired of the comment spam I was receiving, so I have protected this page with a simple calculation exercise. This means that if you want to leave a comment, you'll need to complete the calculation before you hit the Post Comment button.

If you want to object to a comment made by another visitor, be sure to contact me and I'll look into it ASAP. Don't forget to mention the page link, or the Doc ID of the document.

(Plain text only; no HTML or code that looks like HTML or XML. In other words, don't use < and >. Also no links allowed.