Today I worked on a project where I required to display image on the web page. As you know there is not a Html Helper for Images yet. Look at the screen, we can’t see an image here.
Before proceeding in this article, let me share the sample data source here (I can’t share the original data so created a set of dummy data with controller here):
Data Source & Controller
As in the above image, first one (@Html.DisplayFor…) is generated by scaffolding for me (marked as 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.
Add a class file using the following code:
public static class ImageHelper
public static MvcHtmlString Image(this HtmlHelper helper, string src, string altText, string height)
var builder = new TagBuilder("img");
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.
In the view, comment-out the last (html style approach) and use the new extended method for the image, as in:
Note: Please note to use ‘@using MvcApplication8.Models’ namespace on each view page to enable this new HtmlHelper.
If you put a breakpoint on extension method then you will notice that the method returns the exact markup that we need.
Hope this helps.