O'Reilly logo

Programming ASP.NET 3.5, 4th Edition by Jesse Liberty, Dan Hurwitz, Dan Maharry

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Button Controls

Button controls are controls that post the form back to the server, enabling server-side processing to commence. There are three types of ASP.NET button controls, all members of the System.Web.UI.WebControls namespace:

Button

This is the standard button.

LinkButton

The LinkButton control is a cross between a standard button and a HyperLink control (described in the next section). A LinkButton appears to the user as a hyperlink (i.e., the text is colored and underlined), but it performs the standard postback behavior.

ImageButton

The ImageButton control performs the same function as the standard button, except that an image bitmap takes the place of the button on the browser UI. For the ImageButton control, there is no Text attribute but there is an AlternateText attribute, which specifies what text to display on nongraphical browsers instead of the image.

The event handler uses an ImageClickEventArgs event argument rather than the EventArgs argument used in the event handlers for the Button and LinkButton controls. This event argument exposes two fields containing the x and y coordinates of the location where the user clicked on the image.

In addition to all the properties, methods, and events inherited from WebControl, all three button types have the following two events:

Click

This event is raised when the control is clicked and no command name is associated with the Button (i.e., no value has been assigned to the Button control’s CommandName property). The method is passed an argument of type EventArgs.

Command

This event is raised when the control is clicked and a command name such as Sort or Select has been assigned to the Button control’s CommandName property. The event is passed an argument of type CommandEventArgs, which has these two members:

CommandName

The name of the command.

CommandArgument

An optional argument for the command set in the Button control’s CommandArgument property. You could then write a single method to handle the Command event for all the Button controls on your page and have it take its cue from the differing CommandName and CommandArgument values assigned to the different buttons.

Tip

All three types of Button controls implement the IButtonControl interface. This interface requires the Click and Command events, plus properties such as Text and CausesValidation, among others, which we will describe shortly. The IButtonControl interface is what causes a control to act like a button.

Button Behavior

To demonstrate the three Button controls, add to the C4_BasicControls website a new web form called ButtonDemo.aspx. Now add a Button, a LinkButton, and an ImageButton control to the page. Each control will perform the same task: transferring control to another web page.

Tip

For the code in the ButtonDemo website to work correctly, you will need an image file for the ImageButton control. This example uses a file called popflyduck.png, located in the website directory, but you can use any image file you want.

Now switch to Source view if you’re not there already and set the controls’ properties to match those highlighted in Example 4-10.

Example 4-10. ButtonDemo.aspx

<%@ Page Language="C#" AutoEventWireup="true"
   CodeFile="ButtonDemo.aspx.cs" Inherits="ButtonDemo" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title>Button Demo</title>
</head>

<body>
   <form id="form1" runat="server">
   <div>
      <asp:Button runat="server" ID="btnLink"
         Text="Link to target page" onclick="btnLink_Click"
         ToolTip="Click here to go to target page" />
      <asp:ImageButton runat="server" ID="imgLink"
         ImageUrl="~/popflyDuck.png" onclick="btnLink_Click"
         AlternateText="Link to target page"
         ToolTip="Click here to go to target page" />
      <asp:LinkButton runat="server" ID="lnkLink"
         ToolTip="Click here to go to target page"
         Font-Names="Impact" Font-Size="X-Large"
         onclick="btnLink_Click">
            Link to Target Page
      </asp:LinkButton>
   </div>
   </form>
</body>
</html>

All three controls bind the same method, btnLink_Click, to their Click event. This should be added to the code-behind file, ButtonDemo.aspx.cs, as Example 4-11 shows.

Example 4-11. The Click event handler code in ButtonDemo.aspx.cs

using System;

public partial class ButtonDemo : System.Web.UI.Page
{
   protected void btnLink_Click(object sender, EventArgs e)
   {
      Response.Redirect("http://www.ora.com");
   }
}

The resultant web page is shown in Figure 4-6.

The difference between a standard Button control and the other two variants is that both the LinkButton and the ImageButton controls’ functionality is implemented using client-side scripting. This is readily apparent for the LinkButton at least if you look at the markup rendered to your browser resulting from the ButtonDemo.aspx web page, an excerpt of which is shown in Example 4-12. In this listing, the JavaScript “manually” initiates a postback and is called by the <a> element generated by the LinkButton. In effect, this re-creates the automatic postback of the form associated with a standard HTML button because by default, the <a> element generated by the LinkButton will not post a form back when it is clicked.

ButtonDemo.aspx in action

Figure 4-6. ButtonDemo.aspx in action

It also means that if a user has JavaScript disabled in his browser, a LinkButton will not send the user to your intended destination because the postback will not occur.

Remember, this markup is output by ASP.NET, not written by you.

Example 4-12. Excerpt from the HTML and JavaScript generated by ButtonDemo.aspx

<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['form1'];
if (!theForm) {
    theForm = document.form1;
}
function _  _doPostBack(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
        theForm._ _EVENTTARGET.value = eventTarget;
        theForm._ _EVENTARGUMENT.value = eventArgument;
        theForm.submit();
    }
}
//]]>
</script>


<div>
   <input type="submit" name="btnLink" value="Link to target page"
      id="btnLink" title="Click here to go to target page" />
   <input type="image" name="imgLink" id="imgLink"
      title="Click here to go to target page" src="popflyDuck.png"
      alt="Link to target page" style="border-width:0px;" />

   <a id="lnkLink" title="Click here to go to target page"
      href="javascript:_ _doPostBack('lnkLink','')"
      style="font-family:Impact;font-size:X-Large;">
         Link to Target Page
   </a>
</div>

Button Control Extenders

Buttons don’t offer much scope for functional extension. You click them, they post back the form to the server, and that’s it. However, one button-specific extender in the AJAX Control Toolkit—the ConfirmButtonExtender—makes use of the period between the button being clicked and the form being posted to the server. It displays an alert box for the user to confirm that the postback, or whatever action you’ve attached to the Button_Click event, should proceed by clicking OK. If the user clicks Cancel, no postback will occur. Figure 4-7 shows this in action.

The ConfirmButtonExtender in action

Figure 4-7. The ConfirmButtonExtender in action

The ConfirmButtonExtender can target all three types of ASP.NET Button controls, but in the demonstration page shown in Figure 4-7, it has been shown extending only a standard Button control. To build this page, add an AJAX web form called ButtonDemoWithAJAX.aspx to the C4_BasicControls website used in this chapter. Copy the markup for the Button control btnLink from ButtonDemo.aspx and paste it under the ScriptManager control. Next, copy the handler code for its Click event from ButtonDemo.aspx.cs to ButtonDemoWithAJAX.aspx.cs. Run the page to make sure it works as the original page does.

Now drag a ConfirmButtonExtender control to the page. Set its TargetControlID property to btnLink and its ConfirmText property to "Are you sure you want to leave us?" as shown in Example 4-13. Run the page again. This time, when you click the button an alert box pops up asking you to confirm that you want to navigate away. If you click Cancel, the form is not posted back.

Example 4-13. ButtonDemoWithAJAX.aspx

<%@ Page Language="C#" AutoEventWireup="true"
   CodeFile="ButtonDemoWithAJAX.aspx.cs"
   Inherits="ButtonDemoWithAJAX" %>

<%@ Register Assembly="AjaxControlToolkit"
   Namespace="AjaxControlToolkit" TagPrefix="cc1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title>Button Demo With AJAX</title>
   <script type="text/javascript">

      function pageLoad() {
      }

   </script>
</head>
<body>
   
 <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server" />
      <asp:Button runat="server" ID="btnLink"
         Text="Link to target page"
         ToolTip="Click here to go to target page"
         OnClick="btnLink_Click" />
        
      <cc1:ConfirmButtonExtender ID="ConfirmButtonExtender1"
         runat="server" TargetControlID="btnLink"
         ConfirmText="Are you sure you want to leave us?">
       </cc1:ConfirmButtonExtender>
    </div>
    </form>
</body>
</html>

One subtlety to the ConfirmButtonExtender is when the alert box will pop up once the button has been clicked. By default, it appears immediately, but you can delay it to the point immediately before the form is sent back to the server for processing if you set its ConfirmOnFormSubmit property to true. This can be useful for forms that contain client-side validation code that will run after the button is clicked but before the confirm dialog appears.

The ConfirmButtonExtender has one more property—OnClientCancel—the value of which is a client-side script that will run if the user clicks Cancel in the alert box.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required