Wednesday, May 30, 2012

HTML Helper for Action image in MVC (that is, img tag with anchor tag within)

This article aims to explain how can we create and use HTML helper method for IMG html tag, to display an image, and to call a controller action while user clicks over it.

Walkthrough:

Step 1: Create new folder in your MVC structure.



Step 2: Add a new class file "MyHelper.cs" in that folder, and create a "static" class within:
namespace MVC.Infrastructure
{
    public static class MyHelpers
.....

Step 3: Import System, and System.Web.Mvc namespaces in that class.
using System;
using System.Web.Mvc;

Step 4: Write following helper method in MyHelper.cs class.

public static MvcHtmlString ActionImage(this HtmlHelper html, string imagePath, string alt, string cssClass,
            string action, string controllerName,object routeValues)
        {
            var currentUrl = new UrlHelper(html.ViewContext.RequestContext);
            var imgTagBuilder = new TagBuilder("img"); // build the <img> tag
            imgTagBuilder.MergeAttribute("src", currentUrl.Content(imagePath));
            imgTagBuilder.MergeAttribute("alt", alt);
            imgTagBuilder.MergeAttribute("class", cssClass);
            string imgHtml = imgTagBuilder.ToString(TagRenderMode.SelfClosing);
            var anchorTagBuilder = new TagBuilder("a"); // build the <a> tag
            anchorTagBuilder.MergeAttribute("href", currentUrl.Action(action, controllerName, routeValues));
            anchorTagBuilder.InnerHtml = imgHtml; // include the <img> tag inside
            string anchorHtml = anchorTagBuilder.ToString(TagRenderMode.Normal);
            return MvcHtmlString.Create(anchorHtml);
        }

Step 5: Open your razor/ aspx view. Import namespace of above class in your view. (This example deals with razor syntax, but it will be easy for you to convert into aspx, if you are using aspx engine).

@using MVC.Infrastructure

Step 6: Use the created HTML helper to show Image in view, and to call controller action when user clicks it.

@Html.ActionImage("../../Images/logo.png", "Site Logo", "siteLogo", "About", "Home", null)
Here, "Home" is a controller name, and "About" is an action, and it does not have any routeValues so passed as null.

This is all we need to do.
Following is the HTML generated by using this HTML helper:
<a href="/Home/About"><img alt="Site Logo" class="siteLogo" src="../../Images/logo.png" /></a>

You can take advantage of this HTML helper in any view within your MVC application and it will generate HTML image and anchor tags every time for you!

No comments:

Post a Comment

Thanks for visiting my blog.
However, if this helped you in any way, please take a moment to write a comment.

Thanks
Nirman