[MVC 3] Image Preview –HTML Helpers

UPDATE: I have now combined all my MVC Image Handling  blog posts into a Open Source Project. Feel free to check this out once you have read the post.


Original Blog Post:

In my i showed you how to preview an image using a combination of JQuery/AJAX and controller code behind.

This blog post i will show you how to take that a step further and take the HTML code and generate a nice HTML Helper. HTML Helpers are a nice way of re-using your code for future projects.

Lets take a look at the HTML code we wish to generate on the fly:

<input class="upload" type="file" name="imageLoad2" id="File1"/> <img alt="Preview" id="imgThumbnail2" height="126px" width="126px" /> 

This is the code that our JQuery, plays around with to preview an image. Not a lot of code, but wouldn’t be nice to encapsulate this within an Helper?

Firstly what are helpers? Well all they are is code that returns HTML either as a string or Mvchtmlstring. They are useful where you have a lot of conditional logic, plus they also allow you to pass through your model as LINQ Lambda Expression.  Most of the common ones are scaffolded when you create a CRUD controller, that creates your Controller and View using the default T4 Templates.


Ones like:

  1. Html.EditorFor()
  2. Html.LabelFor()
  3. Html.DropDownListFor()

There are lots of them, check them out using your Razor view.


So, to create my custom  helpers, I’ve created a folder in my Project called Helpers and a static class ImageHelpers . Because we are creating a HTML Helper that works like the ones included in the framework, we need to create them using . So you will notice the first parameter is thisHtmlHelper<TModel> helper which will define this extension method as an extension of HtmlHelper. The rest of the parameters allow us to customise the method if needed.

We also have created the method to allow us to pass the generic model and property types. This is useful so we can pass any of our models through, and later on we will add a new T4 template which includes varbinary in the templating. That is a different post though.

 public static class ImageHelpers {
     public static MvcHtmlString UploadImageFor<TModel, TProperty>
       (this HtmlHelper<TModel> helper,
       Expression<Func<TModel, TProperty>> expression, string id = null,
       string name = null, string cssclass = null, string alt = null,
       string imgId = null, string height = null, string width = null)
         const string type = "file";

         if (cssclass == null)
             cssclass = "upload";

         if (id == null)
             id = "File1";

         if (name == null)
             name = "imageLoad2";

         if (alt == null)
             alt = "Preview";

         if (imgId == null)
             imgId = "imgThumbnail2";

         if (height == null)
             height = "126px";

         if (width == null)
             width = "126px";

         var fileBuilder = new TagBuilder("input");
         var imgBuilder = new TagBuilder("img");
         var mergedBuilder = new TagBuilder("p");

         ///Firstly we build the input tag. //--Add the CSS class. fileBuilder.AddCssClass(cssclass);        
        //--Add the name. fileBuilder.MergeAttribute("name", name);        
        //--Add the id. fileBuilder.MergeAttribute("id",id);        
        //--Add the type. fileBuilder.MergeAttribute("type",type);

        ///Secondly we build the img tag. //--Add the alt. imgBuilder.MergeAttribute("alt", alt);        
        //--Add the id. imgBuilder.MergeAttribute("id", imgId);        
        //--Add the height and width. imgBuilder.MergeAttribute("height", height);        
        imgBuilder.MergeAttribute("width", width);

         ///Merge the two together into a p tag. 
        mergedBuilder.InnerHtml += fileBuilder;        
        mergedBuilder.InnerHtml += imgBuilder;        
        return MvcHtmlString.Create(mergedBuilder.ToString());



So, we use three variables to to build an input, image and paragraph tags. This is a nifty little class that allows us to build HTML Elements, and some methods and properties to allow us to quickly to get our desired result, and we return a once we have built it.

We set the default elements to be the names we use in our JQuery, so that the default logic is applied if we have our jquery-previewimage.js used.

We then add our Html helper to our view (After deleting the original code):

          <div class="editor-label"> @Html.LabelFor(model => model.ProfileImage)         
         </div> <div class="editor-field"> @Html.UploadImageFor(model => model.ProfileImage)         

This will generate the original code as seen here when run:


So there we have it, our own HTML Helper which we can re-use for future projects.

3 thoughts on “[MVC 3] Image Preview –HTML Helpers

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.