Wednesday, September 8, 2010

ASP.NET MVC: Creating an ImageLink Extension

It come in my way that when creating an ImageLink in ASP.NET MVC, you cannot directly do something like

<%=Html.ActionLink("<img src=\"~/Content/img.png\" width=\"100\" height=\"50\" />", "Index2", "Home") %>

I'll try to explain this why this will not display an image link.  MVC will encode the string you entered in the linkText parameter of the ActionLink so all tags you entered there will be replace by a Url friendly character e.g. < will become %3C so when it this is displayed in the page, it is displayed as a string.

There is a way of using th ActionLink as the same way but you have string replace your linkText like this.

<%=Html.ActionLink("__IMG__", "Index2", "Home").ToString().Replace("__IMG__", "<img src=\"~/Content/img.png\" width=\"100\" height=\"50\" />")%>

which is very long for me.

Here's my way of doing it easily, by creating an Html Extension for ImageLinks

First Create an HtmlHelper file with a static class, you can put it in a Helpers Folder in your MVC Application.  All of your methods should be static.

public static class HtmlUIHelper
{
public static string ImageLink(this HtmlHelper helper, string ImgPath, string altText, string actionName, string controllerName)
{
var imgTagBuilder = new TagBuilder("img");
imgTagBuilder.MergeAttribute("src", ImgPath);
if(!string.IsNullOrEmpty(CssClass))
imgTagBuilder.AddCssClass(CssClass);
imgTagBuilder.MergeAttribute("alt", LinkText);
string imgTag = imgTagBuilder.ToString();

string imgLnk = helper.ActionLink("_TEMP_", actionName, controllerName).ToString().Replace("_TEMP_", imgTag);
return imgLnk;
}
}

You can now call your extension in any View by Importing the Namespace of you class.

<%@ Import Namespace="MvcApplication1.Helpers" %>

And now you can call your Html Extension for an Image Link.

<%=Html.ImageLink("~/Content/img.png", "LinkImageClass", "Cool Stuffs", "CoolStuffs", "Home") %>

This is just a simple link, you can do more with it, you can add more overloads to it just like the ActionLink extension method of the built-in extensions of ASP.NET MVC.

No comments:

Post a Comment