Sunday, September 9, 2007

Setting image swap on your asp.NET Image Controls - Part 2

In part 1 of this article series, I showed you how to set an image rollover in your ASP.NET (2.0) app with asp.NET HyperLink and Image controls. It's a code behind solution that writes all the javascript for you, making you much more likely to use image rollovers, rather than make them "phase two" of any given project.

As promised, this article shows you how to make it more functional by wrapping the method in a class which is reusable and accessible across your asp.NET application(s).

I'll set up a very simple class in my namespace: Web.Classes.

namespace Web.Classes

{



public class Common

{



public Common() {



}



public static void setMouseOver(HyperLink lnkControl, System.Web.UI.WebControls.Image imgControl, string imgPath, string imgPathOver)

{

lnkControl.Attributes.Add("onmouseover", "document.getElementById('" + imgControl.ClientID + "').src='" + imgPathOver + "';");

lnkControl.Attributes.Add("onmouseout", "document.getElementById('" + imgControl.ClientID + "').src='" + imgPath + "';");

}

}

}

One thing you might notice (if for no other reason than it's highlighted in orange), is that I fully qualified the System.Web.UI.WebControls.Image which shows up as an argument in my method. I've noticed that even when I declare the WebControls Namespace at the top, the compiler can potentially still throw an error due to a conflict with System.Drawing.Image. For simplicity, I didn't use a shorthand in my using statement to solve this, but that's certainly a good option.

Finally, instead of reinventing the wheel on each codebehind, it is not as simple as calling Common.setMouseOver() and providing the appropriate arguments like this:

if(!Page.IsPostBack)
{

Common.setMouseOver(lnkLink1, imgLink1, "
/Images/my_image.png", "/Images/my_image_over.png");
}

My intent with this brief series of articles was to show a simple way of implementing rollover images on your asp.NET pages.

3 comments:

Ben Poole said...

Any developers reading this, please feel free to let me know how I did. I am just getting used to creating blog posts with code in them, and looking at this, maybe there's a better way. I wrote the thing, and might still have a tough time following it due to formatting issues. Thanks.

Dave said...

Super clean solution Ben. I went to write up my own, but figured surely someone has gone down this path before. I came across a lot of junk until I found your page. You saved me a nice chunk of time.

Ben Poole said...

That's great to hear, and I'm glad it helped. Thanks very much for the comment, Dave.