When you think ASP, think...
Recent Articles
All Articles
ASP.NET Articles
ASPFAQs.com
Message Board
Related Web Technologies
User Tips!
Coding Tips
Search

Sections:
Book Reviews
Sample Chapters
Commonly Asked Message Board Questions
JavaScript Tutorials
MSDN Communities Hub
Official Docs
Security
Stump the SQL Guru!
Web Hosts
XML
Information:
Advertise
Feedback
Author an Article
Jobs

ASP ASP.NET ASP FAQs Message Board Feedback ASP Jobs
 
Print this Page!
Published: Thursday, October 21, 2004

Displaying Text in the Browser's Status Bar When Mousing Over a LinkButton

By Scott Mitchell


A New Version of skmLinkButton is Available!
On August 24th, a new version of skmLinkButton was released. This new version builds upon the code presented in this article, adding functionality to remove JavaScript errors when a user attempts to open a LinkButton in a new browser window (by SHIFT+clicking or right-clicking on the link and choosing to Open in a New Window). Be sure to read this article in its entirety first, and then check out Stopping JavaScript Errors When Opening a LinkButton in a New Window.

Introduction


The other day I was perusing the microsoft.public.dotnet.framework.aspnet.webcontrols newsgroup and stumbled upon this question by Brian Hoops:
Is there a way within asp to modify what the status bar text reads when the user hovers above the text for a link-button.

IE: http://www.sitename.com/pagename.aspx rather than javascript:__doPostBack(...)

or do I need to have a javascript onmouseover for every one?

I responded to Brian's question, informing him that there were no built-in properties of the LinkButton Web control that would provide this functionality, and that adding said functionality could be accomplished in one of two ways:
  1. By manually entering the needed JavaScript into the LinkButton's declarative syntax, or programmatically through the LinkButton's Attributes collection, or
  2. By creating a new custom control that derived from LinkButton and included a property like StatusBarText, that could be set to the text to display in the browser's status bar. This extended control, then, would inject the necessary JavaScript.
For the heck of it I whipped up a custom control that extended the LinkButton class and provided the desired behavior. This short article examines this extended LinkButton control, which I call skmLinkButton. skmLinkButton adds to the base LinkButton control by adding four properties:
  • StatusBarText / ShowStatusBarText - the StatusBarText specifies the text to show in the browser's status bar when the LinkButton is moused over. This behavior is only utilized when the ShowStatusBarText is set to True.
  • ConfirmMessage / ShowConfirm - there are times when you may want to display a client-side confirm dialog box upon a user clicking a LinkButton before posting back to the Web server. These two properties allow you to add such functionality, with ConfirmMessage specifying the text to show in the confirm dialog box and ShowConfirm, a Boolean, specifying whether or not to show the confirm dialog box.
This short article provides the code for the skmLinkButton custom server control and demonstrates how to use the control in an ASP.NET page (along with a live demo). Read on to get started with skmLinkButton!

- continued -

Displaying Text in the Browser's Status Bar and Displaying a Client-Side Confirm Dialog Box


Before we can examine the source code for skmLinkButton, let's first take a moment to understand the client-side script needed to display text in the browser's status bar and display a client-side confirm dialog box.

Displaying text in the browser's status bar is as easy as setting the window.status property. For a LinkButton, we'll want the status bar text to be displayed when the user mouses over the LinkButton's rendered hyperlink. Similarly, when the user moves their mouse out of the LinkButton's hyperlink we'll want to clear out the browser's status bar text. To accomplish this we need to add a bit of code to the hyperlink's onmouseover and onmouseout client-side events. Here's what we want the HTML to look like:

<a href="..." 
      onmouseover="window.status='text to display in status bar'; return true;"
      onmouseout ="window.status=''; return true;">
  Text of hyperlink
</a>

A live demo is shown below - just move your mouse over the hyperlink. You'll notice that in your browser's status bar you see the text, "Hi, Mom!"


Move Your Mouse Over Me and Look in Your Browser's Status Bar!


Now that we've seen how to display text in the status bar, let's look at the client-side code for displaying a confirm dialog box. JavaScript includes a function called confirm(message) that causes a modal dialog box to be displayed. This dialog box has two buttons - OK and Cancel - and contains the text specified by the input parameter message. The confirm(message) function returns a Boolean value: true if the user clicked the OK button, false if they clicked Cancel. Confirm dialog boxes are often used to ensure that a user wants to take some action. For example, in An Extensive Examination of the DataGrid: Part 8, I showed how to use confirm dialog boxes to prompt a user to confirm that they really want to delete a record from the DataGrid.

When a user takes an action that causes the Web page's form to be submitted, if some JavaScript event returns false, then the form submission is cancelled. That is, if a LinkButton is clicked, normally it would execute a bit of JavaScript code that would submit the form. However, if there is some JavaScript that returns false, this form submission will be cancelled. Therefore, the call to a JavaScript confirm() function generally takes on the following pattern:

<a href="JavaScript that submits the form" 
      onclick="return confirm('Are you sure you want to submit the form?');"
  Text of hyperlink
</a>

Note that the onclick client-side event handler is returning the result of the confirm() function. Recall that if the user clicks the Cancel button, false is returned, meaning that clicking the Cancel button in the confirm dialog box will cancel the form submission. For more on confirm() and its uses, be sure to check out JavaScript Confirm Form Submission.

Extending the LinkButton Control


One of the main reasons ASP.NET is so powerful is that it's built upon the principles of object-oriented design. The Web controls used in an ASP.NET Web page are merely classes, and as such can be extended through inheritance. (For more on inheritance, be sure to read Ian Stallings' article Using Object-Orientation in ASP.NET.) Thanks to the power of inheritance, we can take an existing control, like the LinkButton, and build upon its existing functionality with minimal effort. I first discussed the ease of extending existing ASP.NET server controls in my article Easily Adding Functionality to ASP.NET Server Controls, and provided a further example in Creating a Row-Selectable DataGrid Control. These same concepts are put to use here in extending the LinkButton class to arrive with the enhanced skmLinkButton.

To start, create a new Web Control Library project in Visual Studio .NET in your language of choice. This will create a class file for you. Now, you want to have your class derive from the System.Web.UI.WebControls.LinkButton class. (Note: the complete code for this article is available as a download at the end of this article.)

The benefit of inheritance is that by simply extending an existing class (LinkButton, in this case), you automatically get all of the built-in functionality of the base class. So, all that's left to do is add our needed functionality. Start by adding four public properties: StatusBarText and ConfirmMessage as string properties, and ShowStatusBarText and ShowConfirm as Booleans. You'll want to have these properties' get and set accessors writing to the ViewState collection, rather than to private member variables, in order to have programmatically changed property values persisted correctly across postbacks. (For more on view state be sure to read Understanding ASP.NET View State.)

The code for your class, at this point, should look like the following (note that the class derives from LinkButton):

using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace skmExtendedControls
{
  public class skmLinkButton : LinkButton
  {
    #region Extended Public Properties
    [Description("The text shown in the browser's status bar."),
    Category("Apperance"), Bindable(true), DefaultValue("")]
    public string StatusBarText
    {
      get
      {
        object o = ViewState["StatusBarText"];
        if (o == null)
          return string.Empty;
        else
          return o.ToString();
      }
      set
      {
        ViewState["StatusBarText"] = value;
      }
    }

    [Description("Specifies if the StatusBarText is shown."),
    Category("Behavior"), Bindable(true), DefaultValue(false)]
    public bool ShowStatusBarText
    {
      get
      {
        object o = ViewState["ShowStatusBarText"];
        if (o == null)
          return false;
        else
          return Convert.ToBoolean(o);
      }
      set
      {
        ViewState["ShowStatusBarText"] = value;
      }
    }
    
    [Description("The text shown in the confirm dialog box."),
    Category("Behavior"), Bindable(true), DefaultValue("")]
    public string ConfirmMessage
    {
      get
      {
        object o = ViewState["ConfirmMessage"];
        if (o == null)
          return string.Empty;
        else
          return o.ToString();
      }
      set
      {
        ViewState["ConfirmMessage"] = value;
      }
    }

    [Description("Specifies if the confirm dialog is shown on button click."),
    Category("Behavior"), Bindable(true), DefaultValue(false)]
    public bool ShowConfirm
    {
      get
      {
        object o = ViewState["ShowConfirm"];
        if (o == null)
          return false;
        else
          return Convert.ToBoolean(o);
      }
      set
      {
        ViewState["ShowConfirm"] = value;
      }
    }
    #endregion

    ...
  }
}

At this point, a page developer could add the skmLinkButton to an ASP.NET page and set any of the LinkButton's properties along with these four, extended properties. However, the skmLinkButton, at this point, would behave no differently than the standard LinkButton, regardless of whether or not these property values were set. We still need to write the code that injects the needed client-side JavaScript into the LinkButton's rendered hyperlink control. This can be accomplished through the AddAttributesToRender() method, whose responisbility is to add the attributes for the rendered HTML element. What we need to do is to override this method, adding our own logic that squirts in the onmouseover / onmouseout / onclick HTML attributes, as needed.

using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace skmExtendedControls
{
  public class skmLinkButton : LinkButton
  {
    ... skmLinkButton Properties ...

    protected override void AddAttributesToRender(HtmlTextWriter writer)
    {
      base.AddAttributesToRender (writer);

      if (ShowConfirm)
        writer.AddAttribute("onclick", 
             string.Concat("javascript:return confirm('", 
                        EscapeJavaScript(ConfirmMessage), "');"));
            
      if (ShowStatusBarText)
      {
        writer.AddAttribute("onmouseover", 
             string.Concat("javascript:window.status='", 
                        EscapeJavaScript(StatusBarText), "';return true;"));
        writer.AddAttribute("onmouseout", 
                        "javascript:window.status='';return true;");
      }
    }

    protected virtual string EscapeJavaScript(string message)
    {
      // Escapes " and new lines in the message, replacing them 
      // with JavaScript equivalents (\" and \n)
      return message.Replace("\"", 
                 "\\\"").Replace(System.Environment.NewLine, 
                                          "\n").Replace("'", "\\'");
    }
  }
}

And that's all there is to it! To complete creation of the skmLinkButton server control, simply build the solution. This will generate an assembly (a .dll file) that you will need to include in the /bin directory of those Web applications that will use skmLinkButton.

Using skmLinkButton in an ASP.NET Page


If you are using Visual Studio .NET, adding skmLinkButton to an ASP.NET page is a breeze. Start by adding skmLinkButton to the Toolbox. This is accomplished by right-clicking on the Toolbox, choosing Add/Remove Items (or Customize Toolbox in VS.NET 2002), and Browsing to the assembly created when you compiled the project. (Note: at the end of this article you can download a pre-compiled assembly for ASP.NET 1.1, along with the complete source code.) After you've added this assembly to the Toolbox, you can simply drag and drop the skmLinkButton onto your page. You can set the skmLinkButton properties through the Properties pane, just like you normally would with a standard LinkButton.

If you are not using Visual Studio .NET to create your ASP.NET pages then you'll need to take the following steps to start using skmLinkButton:

  1. Copy the skmLinkButton assembly to your Web application's /bin directory
  2. Add the following @Register directive to the top of your ASP.NET page:
    <%@ Register TagPrefix="skm" Namespace="Namespace" Assembly="Assembly" %>
    (If you use the source code or pre-compiled assembly available at the end of this article, the namespace and assembly values should be skmExtendedControls.)
  3. Add the skmLinkButton to your ASP.NET page using the following declarative syntax:
    <skm:skmLinkButton runat="server" ... />
The following code snippet demonstrates using skmLinkButton in an ASP.NET Web page:

<%@ Register TagPrefix="skm" Namespace="skmExtendedControls" Assembly="skmExtendedControls" %>

<script language="C#" runat="Server">

  void gotoBlog(object sender, EventArgs e)
  {
    Response.Redirect("http://scottonwriting.net/sowBlog/");
  }

  void confirmedClick(object sender, EventArgs e)
  {
    Response.Write("<h2>You must have been pretty darn sure!</h2>");
  }

  void setStatusBarText(object sender, EventArgs e)
  {
    customStatusBarText.StatusBarText = statusBarText.Text;
  }

</script>

<form runat="server">
	<skm:skmLinkButton runat="server" ShowStatusBarText="True" Text="My Blog" 
	       StatusBarText="Visit ScottOnWriting.NET!" OnClick="gotoBlog" />
	<p>
	<skm:skmLinkButton runat="server" ConfirmMessage="Are you sure!" 
	       ShowConfirm="true" Text="Do You Want to Click Me?" OnClick="confirmedClick" />
	<p>
	<skm:skmLinkButton runat="server" id="customStatusBarText" 
	       ShowStatusBarText="True" Text="Choose the Status Bar Text Below!" />
	<p>
	<asp:TextBox runat="server" id="statusBarText" />
	<asp:Button runat="server" Text="Set Status Bar Text" OnClick="setStatusBarText" />
</form>
[View a Live Demo!]

Conclusion


In this article we looked at how to extend the built-in LinkButton to easily display text in the browser's status bar when moused over. We also saw how to have the LinkButton display a confirm dialog box, only causing a postback when the user clicks OK. Thanks to the power of inheritance, extending the functionality of ASP.NET's Web controls is as easy as creating a new class and tacking on the additional features.

skmLinkButton is just one of my handful of free, open-source ASP.NET controls. You can find a list of my personal control projects at the Scott Mitchell's Code Projects page. Another great source for free ASP.NET server controls is Andy Smith's MetaBuilders site.

A New Version of skmLinkButton is Available!
On August 24th, a new version of skmLinkButton was released. This new version builds upon the code presented in this article, adding functionality to remove JavaScript errors when a user attempts to open a LinkButton in a new browser window (by SHIFT+clicking or right-clicking on the link and choosing to Open in a New Window). Be sure to read this article in its entirety first, and then check out Stopping JavaScript Errors When Opening a LinkButton in a New Window.

Happy Programming!

  • By Scott Mitchell


    Attachments


  • Download the complete source code and pre-compiled assembly (in ZIP format)
  • View a Live Demo!



  • ASP.NET [1.x] [2.0] | ASPMessageboard.com | ASPFAQs.com | Advertise | Feedback | Author an Article