Click here to Skip to main content
15,909,742 members
Articles / Web Development / HTML
Tip/Trick

Custom HTML Helper for MVC Application

Rate me:
Please Sign up or sign in to vote.
4.78/5 (19 votes)
3 Feb 2014CPOL 112.2K   19   6
Add an HTML helper and make it available to your entire application

Introduction

How many times did you wonder how to avoid writing the same chunk of HTML / JavaScript code many times in an MVC Razor view? What if this repetitive task includes some logic?

The solution to avoid this is to build a custom HTML helper to encapsulate everything and make the repetitive task less cumbersome.

Let's say we want to avoid doing this many times inside your views:

HTML
<img src="@myModel.MyObject.ImageSource", alt ="@myModel.MyObject.Imagename",
title ="@myModel.MyObject.ImageDescription" />  

And instead, you want something Razor like that may take care of some logic or validations to avoid error because in the previous snippet, the ImageSource or Imagename or again the description may be null:

HTML
 @Html.Image(@myModel.MyObject.ImageSource, 
@myModel.MyObject.Imagename, @myModel.MyObject.ImageDescription) 
C#
namespace MyNamespace 
 {  
    public static class MyHeleprs
    { 
        public static MvcHtmlString Image(this HtmlHelper htmlHelper, 
        	string source, string alternativeText)
        {
            //declare the html helper 
            var builder = new TagBuilder("image"); 
            //hook the properties and add any required logic
            builder.MergeAttribute("src", source);
            builder.MergeAttribute("alt", alternativeText);
            //create the helper with a self closing capability
            return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));
        } 
    } 
}

To make this helper available in your view, add its namespace as follows:

C#
@namespace MyNamespace 

But if you want it available in all your views, you have to add the namespace not to a specific view but to the collection of namespaces in views' web.config:

HTML
<add namespace="MyNamespace" />   

Now, the Image helper is available everywhere in your views.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) http://www.m2a.ca
Canada Canada
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionnamespace ... Pin
nev3087-Oct-14 11:17
nev3087-Oct-14 11:17 
QuestionGood post Pin
Ayan Chalki25-Jun-14 3:13
Ayan Chalki25-Jun-14 3:13 
Questionit's all about logic Pin
Mack Ait-Aoudia6-Feb-14 10:54
Mack Ait-Aoudia6-Feb-14 10:54 
QuestionNice Intro to extending HtmlHelper, but I think not necessary for the problem shown Pin
igambin5-Feb-14 4:51
igambin5-Feb-14 4:51 
Well as I said, the example is good to show how to extend HtmlHelper, but for the problem you've used I would have used a simple RazorHelper instead.

A good idea in order to support the solution by using a RazorHelper is Saschas proposal to first implement an ImageInfo object.

C#
public class ImageInfo
{
    public string Source { get; set; }
    public string Alt { get; set; }
    public string Description { get; set; }
}


The next step would be to right-click your applications root-item in the Solution Explorer and choose Add => Add ASP.NET folder => App_Code.

Within that folder you create an empty razor-file, e. g. "RazorHelpers.cshtml".

@using MyApp.Models;

@helper ImageLink(ImageInfo info) {
    <img src="@info.Source" alt ="@info.Alt" title ="@info.Description" />
}


And last but not least... wherever you want to display an image just call the razor helper

@RazorHelpers.ImageLink(@myModel.MyObject)


And feel free to add your Models directory to the namespace in the Views/web.config file
<add namespace="MyApp.Models">


I usually prefer to extend HtmlHelper only when I need additional logic. If that is not necessary as you just want to not repeat yourself over and over you should write Razor-Helpers or Editor/Display Templates. In this case a simple RazorHelper would be my choice.

Another nice side effect is that you don't need to rebuild your application if you modify the RazorHelpers code.
QuestionVery good article Mack Ait! Pin
Volynsky Alex4-Feb-14 9:28
professionalVolynsky Alex4-Feb-14 9:28 
QuestionMmmm Pin
Sacha Barber4-Feb-14 2:22
Sacha Barber4-Feb-14 2:22 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.