Custom Html Helpers in MVC

Custom Html Helpers in MVC

  1. Create a static method in a static class.
  2. The First parameter has to be the type to which we can add the extension method.
  3. The Return type should be IHtmlString, that are excluded from html encoding.
  4. To help in the creation of the HTML tags, use the Tab Builder class.
  5. Include the namespace of the Helper method in either the view or the web.config
  6. namespace MVCCustomeHtmlHelper

    {

       public static class CustomHtmlHelpers

       {

          public static IHtmlString Image(this HtmlHelper helper, string src, string alt)

          {

            TagBuilder tagBuilder = new TagBuilder(“img”);

             tagBuilder.Attributes.add(“src”, VartualPathUtility.ToAbsolute(src));

             tagBuilder.Attributes.add(“alt”,alt);

             return new 

                MvcHtmlString(tagBuilder.ToString(TagRenderMode.SelfClosing));

          }

         }

    }


  7. <img src=”@Url.Content(@Model.Photo)” alt=”@Model.AlternateText” />                                                            or

    @Html.Image(Model.Photo, Model.AlternateText)

  8. <system.web.webPages.razor>

       <pages pageBaseType=”System.Web.Mvc.WebViewPage”>

          <namespaces>

             <add namespace=” MVCCustomeHtmlHelper” />

          </namespaces>

       </pages>

    </ system.web.webPages.razor>