Tuesday, April 29, 2008

Adding MouseOver Images to the ASP.NET 2.0 Menu Control

When using the ASP.NET 2.0 Menu control I was surprised to find that it did not support an image mouseover event to swap images. After doing a Google search and finding the post by Stephen Page at http://www.velocityreviews.com/forums/t117199-menu-control-aspnet-20.html I was able to use his example and develop the following code to implement the functionality. I added the custom attributes of ImageUrl and AltImageUrl to the sitemap file and then used the following ItemDataBound event on the menu control.
protected void _siteMenu_ItemDataBound(object sender, System.Web.UI.WebControls.MenuEventArgs e)
{
// Reference the underlying SiteMapNode object...MenuItem item = (MenuItem)e.Item;SiteMapNode nodeFromSiteMap = (SiteMapNode)e.Item.DataItem;
string onImage = "";string offImage = "";string navUrl = "";
// If we have an imageUrl value, assign it to the menu node's ImageUrl propertyif (nodeFromSiteMap["imageUrl"] != null){onImage = System.Web.HttpContext.Current.Request.ApplicationPath + System.IO.Path.Combine("/Images/Elements/", nodeFromSiteMap["imageUrl"]);offImage = System.Web.HttpContext.Current.Request.ApplicationPath + System.IO.Path.Combine("/Images/Elements/", nodeFromSiteMap["altImageUrl"]);}navUrl = nodeFromSiteMap["url"];
// These objects are necessary in order to capture the image object into a rendered html formatstring src = offImage;string toolTip = "";System.Text.StringBuilder sb = new System.Text.StringBuilder();System.IO.StringWriter sw = new System.IO.StringWriter();HtmlTextWriter htmWriter = new HtmlTextWriter(sw);HtmlImage image = new HtmlImage();
image.Style.Add("border-style", "none");MenuItem theMenuButton = new MenuItem();theMenuButton.NavigateUrl = navUrl;image.Src = src;
if (onImage != "" && onImage != null)image.Attributes["onMouseOver"] = "this.src='" + onImage + "';";if (onImage != "" && onImage != null)image.Attributes["onMouseDown"] = "this.src='" + onImage + "';";image.Attributes["onMouseOut"] = "this.src='" + offImage + "';";image.RenderControl(htmWriter);item.Text = sw.ToString();}
If anyone else has other options I would be glad to hear back from you
.

No comments: