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

ASP ASP.NET ASP FAQs Message Board Feedback
 
Print this Page!
Published: Wednesday, September 17, 2003

Creating a RollOver Button Server Control, Part 2

By Scott Mitchell


  • Read Part 1

  • In Part 1 we examined the HTML and client-side JavaScript needed to create a roll-over button. We also looked at the steps we'd need to take to create a roll-over button server control. In this final part we'll examine these steps in detail.

    - continued -

    Adding the ImageUrl and RollOverImageUrl Properties


    The first step in creating our roll-over button server control is to add two properties (in addition to the properties already present in the LinkButton Web control):

    • ImageUrl - the URL of the default image.
    • RollOverImageUrl - the URL of the image to display when the button is "rolled-over" (i.e., the mouse cursor is over the button).

    The code to add these two properties can be seen below:

    [Bindable(true),
      Category("Appearance"),
      DefaultValue("")]
    public string ImageUrl
    {
      get
      {
        object o = ViewState["RollOverImageUrl"];
        if (o != null)
          return (string) o;
        else
          return String.Empty;
      }
    
      set
      {
        ViewState["RollOverImageUrl"] = value;
      }
    }
    
    [Bindable(true),
     Category("Appearance"),
     DefaultValue("")]
    public string RollOverImageUrl
    {
      get
      {
        object o = ViewState["RollOverRollOverImageUrl"];
        if (o != null)
          return (string) o;
        else
          return String.Empty;
      }
    
      set
      {
        ViewState["RollOverRollOverImageUrl"] = value;
      }
    }
    

    This code creates two public properties. The get accessor checks to find the image in the ViewState. If it cannot, it returns the default value (an empty string). The set accessor simply assigns the appropriate ViewState variable the value specified by the user. Realize that it is vital to store the value in the ViewState in order to allow changes to these properties programmatically at various points in the page lifecycle. (For full details, I heartily recommend Developing Microsoft ASP.NET Server Controls and Components.)

    Emitting the Client-Side JavaScript


    The next step is to have the control emit the proper client-side JavaScript. When working with emitting client-side JavaScript from a server control it is important to realize that there may be many instances of the server control on one ASP.NET Web page. Therefore, it is vital to think about whether the script code you need to emit needs to be emitting once for all server controls, or once for each server control. With the roll-over button, the display() function needs to be emitting once for all roll-over button, while the JavaScript to load the specified URLs into the Image objects needs to happen once for every roll-over button.

    The following code illustrates using the Page.RegisterClientScriptBlock() method to add the appropriate JavaScript code:

    protected override void OnPreRender(EventArgs e)
    {
      string imageLoadScriptKey = "rolloverImageBuildingCode" + this.ClientID;
      string script = 
        @"";
      Page.RegisterClientScriptBlock(imageLoadScriptKey, script);
    
      this.Attributes["onmouseover"] = 
          "rolloverServerControl_display('" + this.ClientID + 
                               "_img'," + this.ClientID + "_img_over);";
      this.Attributes["onmouseout"] = 
          "rolloverServerControl_display('" + this.ClientID + 
                               "_img'," + this.ClientID + "_img_out);";
    
      const string displayScriptKey = "rolloverImageLoadScript";
      if (!Page.IsClientScriptBlockRegistered(displayScriptKey))
      {
        script = @"";
    
        Page.RegisterClientScriptBlock(displayScriptKey, script);
      }        
          
      base.OnPreRender (e);
    }
    

    A thorough discussion of the Page.RegisterClientScriptBlock() is a bit beyond the scope of this article. For a good, detailed discussion on emitting client-side code from an ASP.NET server control be sure to read an earlier article of mine: Injecting Client-Side Script from an ASP.NET Server Control.

    One thing to note is that in the control I use the function name rolloverServerControl_display() as opposed to display(), as we discussed earlier. This is so that there is less likelihood of this JavaScript function's name conflicting with the name of an existing JavaScript function in the page. That is, the ASP.NET page developer utilizing the roll-over button might have some client-side JavaScript already in his page. Things can get nasty if this developer chooses to create a JavaScript function with the same name as one I have the server control emit. Hence, I concluded display() would be too likely to conflict with an existing JavaScript function name, but rolloverServerControl_display() was much less likely.

    Rendering the Image


    The final task is to override the LinkButton's RenderContents method. Essentially, if the ImageUrl property is set, we want to have the inner contents of our roll-over button rendered as an <img> tag. If, however, the ImageUrl property is not set, we can just have the roll-over button render like the LinkButton would (by the Text property). This is accomplished with the following code:

    protected override void RenderContents(HtmlTextWriter writer)
    {
    	if (this.ImageUrl != String.Empty)
    	{
    		Image myImage = new Image();
    		myImage.Attributes["name"] = this.ClientID + "_img";
    		myImage.ImageUrl = this.ImageUrl;
    		myImage.AlternateText = this.Text;
    		myImage.Height = this.Height;
    		myImage.Width = this.Width;
    		myImage.ToolTip = this.ToolTip;
    		myImage.RenderControl(writer);
    	}
    	else
    		base.RenderContents (writer);
    }
    

    This method creates a new Image Web control and sets its various properties: the name attribute (essential for the JavaScript function to work!); the ImageUrl, AlternateText, and so on. Finally, it renders itself to the HtmlTextWriter. If, however, no ImageUrl property is specified, the LinkButton's RenderContents() method is invoked instead. A live demo is available to show the roll-over button in action.

    Using the Roll-Over Button Server Control in an ASP.NET Web Page


    In order to start using this roll-over button in an ASP.NET Web page you need to download the assembly at the end of this article. Copy this assembly to your Web application's /bin directory. (Alternatively you can download the source code and compile the assembly yourself...) Then, to use it in an ASP.NET Web page, add the following to the top of the Web page:

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

    You can then use the control in your ASP.NET Web page by adding:

    <skm:RollOver runat="server" id="RollOver1" ImageUrl="..." RollOverImageUrl="..." ... />

    If you are using Visual Studio .NET, first add the assembly to the Web project's References folder. Then, add the roll-over button to the Toolbox by right-clicking on the Toolbox and choosing, Add/Remove Item from Toolbox. Click browse and locate the assembly and click OK. Once you have added the roll-over button assembly you can add the roll-over button to an ASP.NET Web page by simply dragging and dropping the roll-over icon from the Toolbox onto the Designer.

    Conclusion


    In this article we saw how to create a roll-over button that, when clicked, causes a postback, just like the LinkButton. Clearly creating this server control was a snap due to inheritance since we were able to utilize the built-in functionality of the LinkButton Web control. All we had to do was add a couple of properties, emit some client-side script, and override the LinkButton's RenderContents() method.

    Happy Programming!

  • By Scott Mitchell


    Attachments


  • Download the complete source code
  • Download the compiled assembly (in ZIP format)


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