MVC 3 Helper for Hover Images...

Hi Folks,

In this post I will talk about something that I haven't found on the internet, which is quite simple to do, which is a MVC Helper for creating a Hover image button...

If you are a professional developer and work in a team, you must have people which make the graphical stuff of your website, because most developers (like me) just don't like it, it's just a completely separate job.

This code assumes that you already understand MVC.

So here are my images, one named OK.png and the other OK_Hover.png, that are located on the Content/Images/Buttons folder.
Now what I want do do is to use my helper (which appears on listing 1), to use it in my razor page, and that upon a click will redirect me to the corresponding view.
So in my index.cstml I have:
@using HoverImageHelper.Helpers;
ViewBag.Title = "Index";


@Html.ImageButton("OK", "OK")
So the first parameters corresponds to my PNG file, and the second to my action.
Listing 1

/// This function creates an image button with a hover, based on a an image name (must be .PNG)
/// and its corresponding hover image

public static MvcHtmlString ImageButton(this HtmlHelper helper, string imageName, string actionName, object routeValues)
//Gets the action name and routes
var urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
var url = urlHelper.Action(actionName, routeValues);
//Creates the image tag
var imgTag = new TagBuilder("img");
var imageUrl = string.Format("/Content/Images/{0}.png", imageName);
imgTag.Attributes.Add("src", imageUrl);
imgTag.Attributes.Add("onmouseover", "this.src='" + imageUrl.Replace(".", "_hover.") + "'");
imgTag.Attributes.Add("onmouseout", "this.src='" + imageUrl + "'");
imgTag.Attributes.Add("border", "0");
//Creates the link tag
TagBuilder imglink = new TagBuilder("a");
imglink.MergeAttribute("href", url);
imglink.InnerHtml = imgTag.ToString(TagRenderMode.SelfClosing);
return MvcHtmlString.Create(imglink.ToString());
And a corresponding overload (which I use on this example):
Listing 2
public static MvcHtmlString ImageButton(this HtmlHelper helper, string imageName, string actionName)
return ImageButton(helper, imageName, actionName, null);
Happy programming!!!
You can grab the full code here:


Posts les plus consultés de ce blog

How to encrypt to a url safe string...

How to delete many-to-many relationship in Entity Framework...

Html to Image...