Tuesday, 28 April 2015

Custom HTML Helpers in ASP.NET MVC

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:

  <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.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));
        }
    }
}

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

@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:

<add namespace="MyNamespace" />

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

2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Please review the line for adding namespace. It should be @using MyNamespace no?

    ReplyDelete

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (47) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (49) CD (1) CI (2) CloudComputing (2) Coding (8) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (19) Entity Framework (4) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (10) microservice (4) Mongodb (1) MVC (46) NodeJS (8) React (10) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (3) UI (1) UnitTest (2) WCF (14) Web Api (16) Web Service (1) XMl (1)

Dotnet Guru Archives