Tuesday, May 26, 2015

Custom HTML Helper for MVC Application

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.

No comments:

Post a Comment

can you please explain me Backpropagation & Gradients in layman language as simple as possible

 Absolutely! Let’s break down backpropagation and gradients in the simplest possible way , like we’re teaching a curious 10-year-old. 🎯...