Custom Html Helper

  In this post I will explain how to create How to create our own HTML controll in our MVC 4 application.
   
MVC have some pre define html helper.If y want to render image in you application every time use the following line in every view
<img src="@Model.ImageSource", alt ="@Model.Imagename",
title ="Model.ImageDescription" />
 
Now see how to avoid how to  write lengthy code using Custom html helper.

First create class name as MyOwnHtmlHelper

namespace MyFirstCustomHelpers
 {  
    public static class MyOwnHtmlHelper
    { 
        public static MvcHtmlString MyOwnImage(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));
        } 
    } 
}
 
 
 
Next step, we want to add the namespace in web.config file then only we can easily use the controll in all view

<system.web.webPages.razor>
<host factoryType=”System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc,
Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35″ />
<pages pageBaseType=”System.Web.Mvc.WebViewPage”>
<namespaces>
<add namespace=”System.Web.Mvc” />
<add namespace=”System.Web.Mvc.Ajax” />
<add namespace=”System.Web.Mvc.Html” />
<add namespace=”System.Web.Optimization”/>
<add namespace=”System.Web.Routing” />
<add namespace=”MyFirstCustomHelpers”/>
</namespaces>
</pages>
</system.web.webPages.razor>

Next 
Call our Custom Html Helper method in the index view like following

@Html.MyOwnImage(@Model.ImageSource,”@Model.Imagename”)

No comments:

Post a Comment