HTML Helper For Image (@Html.Image): Developing Extension in MVC

Today I worked on a project where I am required to display an image on the web page. As you know there is not a HTML Helper for images yet. Look at the following screen, we can't see an image here:

Developing-Extension-in-MVC.png

Before proceeeding in this article, let me share the sample data source here (I can't share the original data so I created a set of dummy data with a controller here):

Data Source & Controller

Extension-in-MVC.gif

View

Html-Helper-for-Image2.png

As in the above image, the first one (@Html.DisplayFor…) is generated by scaffolding for me (marked as a comment in the above view) and the second one is an alternative that will work.

So, we don't have a HTML helper to deal with images using Razor syntax! Wait wait. We can develop an extension method for this that will allow us to work with images. Let's get started.

Step 1: Add a class file using the following code:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

 

namespace MvcApplication8.Models

{

    public static class ImageHelper

    {

        public static MvcHtmlString Image(this HtmlHelper helper, string src, string altText, string height)

        {

            var builder = new TagBuilder("img");

            builder.MergeAttribute("src", src);

            builder.MergeAttribute("alt", altText);

            builder.MergeAttribute("height", height);

            return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));

        }

    }

}

The above "Image" function has the "MvcHtmlString" type and will accept a four-parameter helper (helper type "image"), src (image path), altText (alternative text) and height (height of image) and will return a "MvcHtmlString" type.

Step 2: In the view, comment-out the last line (HTML style approach) and use the new extended method for the image, as in:

Html-Helper-for-Image3.gif

Note: Please note to use "@using MvcApplication8.Models" namespace on each view page to enable this new HtmlHelper.

Step 3: If you put a breakpoint on the extension method then you will notice that the method returns the exact markup that we need.

Extension-method-in-MVC.gif

Hope this helps.


Similar Articles