Custom HTML Helper for MVC Application

How many times you wonder on how to avoid writing the same HTML/JavaScript code many times in an MVC Razor view? What if this repetitive task can be as simple as building a custom HTML helper to encapsulate everything and make repetitive task less arduous.

So, let’s say we want to avoid doing this code many times in your views:

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

So you want something Razor like that may take care of some logic or validation error in the previous snippet.

@Html.Image(@myModel.MyObject.ImageSource, 
@myModel.MyObject.Imagename, @myModel.MyObject.ImageDescription)
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));
        } 
    } 
}

Read the rest of the code here: http://www.codeproject.com/Tips/720515/Custom-HTML-Helper-for-MVC-Application

Leave a Reply

Your email address will not be published. Required fields are marked *