default heading
Google


 

Article Rating:  3.63

Empowering the ASP.Net Button Web Control, Confirm?...

Learn how to create an ASP.Net confirm button using a combination of VB and JavaScript code


By: Victor Rubba Date: January 11, 2003 Download the code. Printer Friendly Version

Empowering the ASP.Net Button Web Control, Confirm?

Having done my share of frolicking in asp pages and JavaScript over the years, I’d come to expect and grow rather dependent on the good ol’ alert() and confirm() functions. Getting deep into ASP.Net, I discovered, much to my horror, that since the Button Web Control is a server side control, a messagebox function would result in something popping up on the server, rather than the web client. How could this be, I wondered? Convinced that there must be an answer, I did a little bit of research and came up with a simple yet effective alternative.

Ok, let’s start off with a new Visual Basic ASP.NET Web Application, called ConfirmationButton. We’ll keep Webform1, as well as add a second webform called main.aspx, and a class called confirmbutton.vb.

Let’s get right to it! The confirmbutton.vb class. Here’s the code:

Public Class ConfirmButton
  Inherits System.Web.UI.WebControls.Button

  Private _Message As String

  Public Property Message() As String
    Get
      Return _ButtonMessage
    End Get
    Set(ByVal Value As String)
      _ButtonMessage = Value
    End Set
  End Property

Protected Overrides Sub OnPreRender(ByVal e As EventArgs)
  Page.RegisterClientScriptBlock( _
  __doAlert" _
  "<script language=""javascript"">"& vbCrLf & _
  "function __doConfirm(btn){" & vbCrLf & _
    "var answer = confirm(""" + _ButtonMessage+ """);" & vbCrLf & _
    "if (answer){" & vbCrLf & _
      "return true;}" & vbCrLf &_
    "else{" & vbCrLf & _
      "return false;}}" & vbCrLf & _
    "</script>" _
    )

    Me.CausesValidation = False
    Me.Attributes("onclick") = "return __doConfirm(this);"

    'The MyBase keyword behaves like an object variable referring
    'to the base class of the current instance of a class

    MyBase.OnPreRender(e)

  End Sub

End Class

Let’s break it down. First of all you can see that we are creating a Derived Class, building on the System.Web.UI.WebControls.Button Base Class (using Inherit). Nothing too complicated about this. Next we declare a private variable called _ButtonMessage, which will hold the value of a new Custom property we will be adding to our derived button class:

Public Property Message() As String
  Get
    Return _ButtonMessage
  End Get
  Set(ByVal Value As String)
    _ButtonMessage = Value
  End Set
End Property

So far, still fairly self-explanatory. Next in the code, you can see that we override the OnPreRender procedure with our own flavor. In here 4 things happen:

  1. Create a custom javascript function that will be inserted into the page before it is returned to the client
  2. Set the property CausesValidation to False, regardless of what it’s set to at design time (required for validation to function properly.. more on this later)
  3. Set the attribute of the onClick event to trigger the javascript function we just inserted
  4. Call the OnPreRender subroutine in the base class.

Let’s take a closer look at the javascript. Once you remove all the vbCrLf’s and quotes, this is what it looks like:

<script language="javascript">
function __doConfirm(btn){
var answer = confirm("Are you sure you wish to submit?");
if (answer)
{
return true;
}
else
{
return false;
}
} </script>

A simple javascript confirm function that returns either true or false. If true, it returns true and the click command carries on to carry out any code in the click event. If false, it simply aborts.

Allright, so now that you’ve finished building this custom button class, let’s see how we can add it to a webform and test it out.

Bring up the webform1.aspx in HTML mode. Insert the following line at the very top of your code:

<%@ Register TagPrefix="ASPCustom" namespace="ConfirmationButton" assembly="ConfirmationButton"%>

Ensure that namespace and assembly match the name of the project. Tagprefix can be anything you want, and will replace the typical <asp:button… with <ASPCustom:ConfirmButton…

Here’s the HTML code page:

<%@ Page Language="vb" AutoEventWireup="false" Codebehind="WebForm1.aspx.vb" Inherits="ConfirmationButton.WebForm1"%>
<%@ Register TagPrefix="ASPCustom" namespace="ConfirmationButton" assembly="ConfirmationButton"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>WebForm1</TITLE>
<META content="Microsoft Visual Studio.NET 7.0" name="GENERATOR">
<META content="Visual Basic 7.0" name="CODE_LANGUAGE">
<META content="JavaScript" name="vs_defaultClientScript">
<META content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
</HEAD>
<BODY MS_POSITIONING="GridLayout">
<FORM id="Form1" method="post" RUNAT="server">

<ASPCUSTOM:CONFIRMBUTTON id="Confirmbutton1" style="Z-INDEX: 101; LEFT: 316px; POSITION: absolute; TOP: 81px" RUNAT="server" MESSAGE="Are you sure you wish to submit?" TEXT="Submit" WIDTH="122px">
</ASPCUSTOM:CONFIRMBUTTON>

<ASP:TEXTBOX id="TextBox1" style="Z-INDEX: 103; LEFT: 121px; POSITION: absolute; TOP: 79px" RUNAT="server" WIDTH="169px" HEIGHT="26px">
</ASP:TEXTBOX>

<ASP:REQUIREDFIELDVALIDATOR id="RequiredFieldValidator1" style="Z-INDEX: 102; LEFT: 170px; POSITION: absolute; TOP: 105px" RUNAT="server" CONTROLTOVALIDATE="TextBox1" ERRORMESSAGE="Your Name is a required field." Font-Size="XX-Small">
</ASP:REQUIREDFIELDVALIDATOR>

<ASP:LABEL id="Label1" style="Z-INDEX: 104; LEFT: 32px; POSITION: absolute; TOP: 82px" RUNAT="server">
Your Name:
</ASP:LABEL>
</FORM>
</BODY>
</HTML>

The only other relevant code on this page are the following lines:

<ASPCUSTOM:CONFIRMBUTTON
  id="cmdSubmit"
  style="Z-INDEX: 101; LEFT: 316px; POSITION: absolute; TOP: 81px"
  RUNAT="server"
  CAUSESVALIDATION="False"
  MESSAGE="Are you sure you wish to submit?"
  TEXT="Submit"
  WIDTH="122px">
</ASPCUSTOM:CONFIRMBUTTON>

As you can see we’ve referenced the ConfirmButton class using the ASPCustom tag prefix. We’ve added and set the Message property. Now let’s go to the designer view, and double click on the Submit Button to bring up the OnClick event. Type in the following code.

Private Sub cmdSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSubmit.Click
  Me.Validate()
  If Me.IsValid Then
    'Execute subsequent code in here
    Response.Redirect("main.aspx?Name=" & TextBox1.Text)
  End If
End Sub

A quick discussion on validation. Originally I created this confirm button on a form that had no field validators and it worked great… until I added a field validator. What ASP.NET does behind the scenes when validation controls exist, is add an autogenerated onClick event for each button. This OnClick event would supercede the custom OnClick event I had created in my custom class. So to overcome this I did the following:

  1. add the Me.CausesValidation = False to the OnPreRender routine of my class.
  2. added the Me.Validate() and Me.IsValid code to the onClick event behind the page to simulate the now missing autogenerated validation code behind the button.

Finally I added a single label webcontrol (label1) to main.aspx, grabbed the name from the querystring on PageLoad and set the text of the label as follows:

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
   Label1.Text = "Nice to meet you, " & Request.QueryString("Name").Trim & "!"
End Sub

That about covers it. I’ve found this ConfirmButton quite useful and have incorporated into most of my projects. It’s great for confirming cancel and submit actions, as well as saving the user from themselves on that ever tempting, far too close to the submit, delete button. Cheers.

Here’s what the pages should look like:





You may download the code here.

 
Please Rate This Article Poor           Excellent
 
 
 
 
 
   © Copyright 2002-2012 DotNetJohn.com LLC
Terms of Use Privacy Policy