To read the article online, visit http://www.4GuysFromRolla.com/articles/012809-1.aspx

RedirectButton - Redirect Users With the Click of a Button

By Scott Mitchell


Introduction


Virtually every ASP.NET developer has, at one point or another, created a page with a Button control that, when clicked, redirects the user to some other page, perhaps sending along a value entered by the user through the querystring. The typical pattern for implementing such behavior is to add a Button to the page and create a Click event handler that executes a Response.Redirect(url). If the redirect incorporates some input from the user, then this pattern is expanded to include the addition of a TextBox or some other control to the page and a Response.Redirect(url) statement that includes this control's value.

While this approach certainly works, it's not without a couple of flaws. Firstly, this approach involves a needless round-trip to the server: clicking the Button causes the browser to re-request the page and the response from the server is simply, "Please go to url." Ideally, when the Button was clicked the browser would immediately request the final destination URL rather than have to do a postback to find out the final destination URL. Second, this approach can lead to a confusing user experience in scenarios where there are multiple TextBoxes on the page and multiple Buttons because there may not be the expected correspondence between hitting Enter in a TextBox and having the associated Button control "clicked." Consider a website with a master page that has a TextBox and Button for searching the site. Now imagine an ASP.NET page that uses this master page and includes a number of TextBoxes and a Button. If the user hits enter after typing in a search query there is a postback, what Button does ASP.NET consider has been "clicked," the search query button or the submit button in the web page? (See Enter and the Button Click Event for a more in-depth look at this undesirable behavior.)

I've created a custom ASP.NET server control I call RedirectButton that offers a simple way to create a Button control that, when clicked, redirects a user to a specified URL and avoids those shortcomings just discussed. This article examines how this control works and shows how to use it in an ASP.NET web application. The complete source code for RedirectButton, along with a demo application, is available for download at the end of this article. Read on to learn more!

Exploring the RedirectButton Control's Functionality


In a nutshell, the RedirectButton control renders as a button HTML element (<input type="button" ... />) that includes JavaScript in its onclick client-side event handler that redirects the visitor to a specified URL. Let's look at a few examples of using this control, starting with the most basic one: a RedirectButton that, when clicked, sends the user to a static URL.

The RedirectButton control has a property named RedirectUrl, which is required. This property value specifies where the user is taken to when the RedirectButton is clicked. For example, if you added a RedirectButton to an ASP.NET page, set the RedirectUrl property to "http://www.google.com/", the Text property to "And We're Off to Google!", and then visited the page through a browser, you would see a page with a button titled "And We're Off to Google!". Clicking it would send you to Google's homepage.

<cc1:RedirectButton runat="server" ID="btnToGoogle"
               RedirectUrl="http://www.google.com/"
               Text="And We're Off to Google!"
/>

The RedirectButton appears like any other Button control.

Clicking the RedirectButton sends the visitor to Google's homepage.

Typically, redirecting a user to another page when clicking a Button control requires that you create a Click event handler and issue a Response.Redirect. But in this example we didn't have to write a line of code. Moreover, clicking the "And We're Off to Google!" button does not cause a postback, but rather sends the user directly to Google's homepage. What's going on here?

The RedirectButton control renders an HTML button that contains the following client-side onclick event handler:

<input type="button" name="btnToGoogle" value="And We're Off to Google!" id="btnToGoogle"
       onclick="skm_Redirect('http://www.google.com/', '');" />

The skm_Redirect JavaScript function is defined a JavaScript include file, which gets automatically added to the page by the RedirectButton server control. The skm_Redirect function accepts two input parameters: the URL to redirect the user to and the ID of an associated input control, if any. In this example there is no associated input control (we'll discuss this feature shortly). The user is sent to the URL - http://www.google.com/, in this example - via JavaScript:

document.location.href = redirectUrl;

Sending User Input in the Querystring


The impetus for creating the RedirectButton control materialized when I was building a website that used Google's Custom Search Engine to implement site search. To use Google's Custom Search Engine you create a page on your website with an IFRAME and then visit that page passing along the search criteria (and other information) through the querystring. The Google Custom Search Engine then displays pages on your site that match the search criteria. (See Implementing Search in ASP.NET with Google Custom Search to learn how to add Google's Custom Search to your website.)

When building this site I added a search box and button to the master page, the idea being that on every page the user could see a search box, type in her query, click the button, and see the results. I initially made the search button a Button Web control and added a Click event handler in the master page's code-behind class that redirected the user to the search results with the values entered in the search box passed along in the querystring. This worked well when the user typed in a search query and clicked the search button, but if they typed in the search query and then pressed Enter, the behavior was more erratic. If the ASP.NET page the user was visiting had another Button on the page, hitting Enter in the search query box submitted the form but fired the Click event of the Button on the page, and not the search buttons. This understandably confused the site's users.

The RedirectButton control helps solve this problem. You can associate a TextBox or DropDownList control with the RedirectButton control via the AssociatedControlId property. When using this property you also need to set the RedirectButton's QueryStringParameterName property, which indicates the querystring parameter name used when sending this value. For example, imagine that we wanted to have a TextBox and a Button that, when clicked, redirected the user to the page ~/SearchResults.aspx passing the value entered by the user in a querystring parameter named query, such as: ~/SearchResults.aspx?query=TextEnteredByUser. To achieve this we'd add a TextBox to the page named, say, txtSearchQuery, and then a RedirectButton. Next, we'd set the RedirectButton's RedirectUrl property to "~/SearchResults.aspx", the AssociatedControlId property to "txtSearchQuery", and the QueryStringParameterName property to "query":

Search: <asp:TextBox ID="txtSearchQuery" runat="server"></asp:TextBox><br />

<cc1:RedirectButton runat="server" ID="btnSearchRedirectButton"
               AssociatedControlId="txtSearchQuery"
               QueryStringParameterName="query"
               RedirectUrl="~/SearchResults.aspx"

               Text="Go!" />

This page, when visited through a browser, would produce the following markup for the RedirectButton control:

<input type="button" name="btnSearchRedirectButton" value="Go!" id="btnSearchRedirectButton"
      onclick="skm_Redirect('SearchResults.aspx?q={AssocCtrlValue}', 'txtSearchQueryRedirectButton');" />

Note that the call to the skm_Redirect function passes in the placeholder {AssocCtrlValue} where the user's input should be placed, as well as the ID of the associated input control (txtSearchQueryRedirectButton). The skm_Redirect function dynamically replaces the {AssocCtrlValue} placeholder with the value in the associated control. What's more, the RedirectButton control adds JavaScript to the associated TextBox so that when the user presses the Enter key it "clicks" the associated button.

"Clicking" a Button When Hitting Enter
As noted, the RedirectButton control's AssociatedControlId property allows the page developer to define a TextBox control that causes the RedirectButton to be "clicked" when the Enter key is pressed. Another way to accomplish this same behavior but with the standard ASP.NET Button control is to put the TextBox and Button in a Panel control and then set the Panel's DefaultButton property to the ID of the Button control. This adds JavaScript to the page that causes the specified Button to be "clicked" when the user presses the Enter key in the TextBox in the Panel.

Of course, there is a key difference between "clicking" the RedirectButton and "clicking" a standard ASP.NET Button. Namely, "clicking" the RedirectButton (either directly or from pressing Enter in the associated TextBox) does a client-side redirect, whereas a standard Button control causes a postback. For a more detailed look at the DefaultButton property and how it works see my blog entry, The DefaultButton Property.

Let's put this concept in action. When you search Google you are taken to the search results page with the search query passed through the querystring like so: http://www.google.com/search?q=SearchQuery. We can let users search Google from our site using a TextBox control and the RedirectButton. Simply add a TextBox to the page and set its ID to txtSearchGoogle. Next, add a RedirectButton and set its RedirectUrl property to "http://www.google.com/search", its QueryStringParameterName to "q", and its AssociatedControlId property to "txtSearchGoogle". Now when the user enters a search term in the textbox and clicks the button or presses Enter after entering their search term, they are redirected to the Google search results.

Search Google: <asp:TextBox ID="txtSearchGoogle" runat="server"></asp:TextBox>

<cc1:RedirectButton runat="server" ID="btnSearchGoog"
               AssociatedControlId="txtSearchGoogle"
               QueryStringParameterName="q"
               RedirectUrl="http://www.google.com/search"
               Text="Go!" />

Search Google on the term Scott Mitchell

Google's search results are displayed.

You can pass additional opaque querystring data using the RedirectButton's AdditionalQuerystringContent property. For example, the above example sends just the q=searchTerm value in the querystring (e.g., http://www.google.com/search?q=Scott%20Mitchell). You can pass additional information through the querystring - such as safe=on to perform a "Safe Search" - by setting AdditionalQuerystringContent to "safe=on". Doing so will modify the URL the user is sent to to include this querystring data: http://www.google.com/search?q=Scott%20Mitchell&safe=on

Adding the skmControls2 Library to Your Web Application


The download available at the end of this article includes the source code and a pre-compiled assembly for skmControls2, a suite of custom ASP.NET controls I've developed over the years. To use the skmControls2 controls in an ASP.NET website, copy the DLL to the website's Bin directory and then add the following @Register directive to the tops of the .aspx pages where you want to use the controls:

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

(Alternatively, you can add this @Register directive in the Web.config file so that you do not need to add it to every ASP.NET page that uses the controls. See Tip/Trick: How to Register User Controls and Custom Controls in Web.config.)

You can then add the RedirectButton markup we examined earlier in this article in the Source view, after which you can now go to the Design view and view and set its properties via the Properties window. (You can also add the control to your Toolbox in Visual Studio by: right-clicking on the Toolbox; selecting Choose Items; going to the Browse tab; and browsing to the skmControls2.dll assembly. Once added to the Toolbox you can add the Chart control to a page by dragging it from the Toolbox onto the page's Design surface or declarative markup portion.)

Future Enhancements


Currently, the RedirectButton does not participate in any client-side validation of data. That is, if the RedirectButton is associated with a TextBox and that TextBox has a RequiredFieldValidator control on it, it doesn't matter whether the user has inputted anything into the TextBox when the RedirectButton is clicked - the redirect's going to happen regardless. In the future I'd like to have the RedirectButton utilize the client-side validation functionality of the validation controls. I'd also like to enhance the control (or add new controls) so that the same functionality is available with hyperlinks and images, much like with ASP.NET's LinkButton and ImageButton controls.

If you have any other ideas for improvements, drop me a line - mitchell@4guysfromrolla.com.

Happy Programming!

  • By Scott Mitchell


    Attachments:


  • Download the skmControls2 Library (includes control source code and demo app)
  • Further Reading


  • An In-Depth Look at HTTP Redirection
  • Implementing Search in ASP.NET with Google Custom Search
  • Enter and the Button Click Event
  • Two Common Pitfalls When Submitting a Web Form Using the Enter Key
  • Article Information
    Article Title: ASP.NET.RedirectButton - Redirect Users With the Click of a Button
    Article Author: Scott Mitchell
    Published Date: January 28, 2009
    Article URL: http://www.4GuysFromRolla.com/articles/012809-1.aspx


    Copyright 2014 QuinStreet Inc. All Rights Reserved.
    Legal Notices, Licensing, Permissions, Privacy Policy.
    Advertise | Newsletters | E-mail Offers