-1

Today, I interact with one problem where I need my own html helper which trace data as I required.

I want to know, how to create customized html helper .

How to create customized @Html. with custom code?

Opal
  • 81,889
  • 28
  • 189
  • 210

2 Answers2

2

An Example of basic but useful html helper for Images :

Custom Helper :

using System;
using System.Web.Mvc;

namespace HelperApplication.Helpers
{
     public static class CustomHelpers
     {
          public static string Image(string src, string alt = "Image", int width = 50, int height = 50)
          {
               return String.Format("<img src='{0}' alt=’{1}’ width=’{2}’ height=’{3}’/>", src, alt, width, height);
          }
     }
}

View :

<div>
 <span>Image with default values for alt, width, height</span>
      @Html.Raw(@CustomHelpers.Image("imagePath"))
</div>
<div>
 <span>Image with width=100 and height=100</span>
      @Html.Raw(@CustomHelpers.Image("imagePath","Image With alt",100,100))
</div>

Beacause custom html helper is returning simple string then we can encode it to html string using @Html.Raw() helper and include required namespace HelperApplication.Helpers in your view where you want to use custom html helper..

Kartikeya Khosla
  • 18,743
  • 8
  • 43
  • 69
  • 2
    This won't work in ASP.NET MVC because the return type of your helper is string, which will be escaped by default. See http://stackoverflow.com/a/4596957/64096 , you should return `IHtmlString` (or a derived type). Also, this is not an extension method so you need to include the class name when you invoke it. Html helper methods are usually extension methods on HtmlHelper so you can access them through `@Html.MyHelper(...)` – Marnix van Valen Aug 07 '14 at 09:35
  • This fixes the formatting in your sample code, but it doesn't make the code in your view look any better. Why not use `new HtmlString(...)` in the helper and get rid of the `Html.Raw` call? Note that you still need to include the class name before the call to `Image` since it's a static method on a static class. – Marnix van Valen Aug 07 '14 at 09:45
  • @MarnixvanValen..yes ofcourse you have to include namespace in order to use custom helper...i m here is just giving basic usage of custom html helper – Kartikeya Khosla Aug 07 '14 at 09:47
1

As Exception's answer shows, there's more than one way to write an HTML helper. The convention used in MVC however is to write them as extension methods on HtmlHelper or HtmlHelper<TModel>.

The most important thing you need to keep in mind is escaping your HTML content correctly. The Razor view engine will, by default, escape all plain text (string). So you either need to wrap your content with a call to Html.Raw() inside your view or use an implementation of IHtmlString.

There is more to it though. You also need to take into account that HTML has certain requirements when you put text in attributes. HtmlHelper provides methods to escape this correctly.

To expand upon Expection's code sample, that would look like this:

using System;
using System.Web.Mvc;

namespace HelperApplication.Helpers
{
   public static class CustomHelpers
   {
      public static IHtmlString Image(this HtmlHelper html, string src, string alt = "", int width = 50, int height = 50)
      {
           return new MvcHtmlString( 
              string.Format("<img src='{0}' alt='{1}' width='{2}' height='{3}'/>",
              html.AttributeEncode(src), 
              html.AttributeEncode(alt), 
              width, 
              height) );
      }
   }
}

You'd use this in the view like so:

<div>
  <span>Image with default values for alt, width, height</span>
    @Html.Image("/img/logo.jpg")
</div>
<div>
  <span>Image with width=100 and height=100</span>
    @Html.Image("/img/warning.png","Don't try this at home",100,100)
</div>

If you want more flexibility, there's also a TagBuilder that can help you generate correct markup:

 public static IHtmlString Image( this HtmlHelper html, string path, object htmlAttributes )
 {
    TagBuilder tagBuilder = new TagBuilder( "img" );
    var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes( htmlAttributes );
    tagBuilder.MergeAttributes( attributes );
    tagBuilder.Attributes["src"] = path;
    return new MvcHtmlString( tagBuilder.ToString() );
 }

Though it's indeed a bit more complex, this will allow you a great deal of flexibility. It will allow you to specify any property, even custom properties for client side frameworks and any CSS that you need to apply to your element. To get the same results as in the previous sample, you'd invoke this helper like so:

<div>
  <span>Image with alt attribute and CSS for height and width</span>
    @Html.Image("/img/warning.png", new { alt = "Don't try this at home", style="width:100px; height:100px" })
</div>
Marnix van Valen
  • 13,265
  • 4
  • 47
  • 74
  • 1
    @Exception I credited you for the code sample twice in my answer. This site is not about personal glory, it's about helping each other. I tried to help you out by providing constructive comments and an edit. In the end your solution is not how I implement HTML helpers so I've added my way of doing this as another answer. In the end I think it's more helpful to show two ways of doing the same thing so people can see the difference and decide what approach works best for them. – Marnix van Valen Aug 07 '14 at 12:53
  • But i don't think that you are doing something different in your answer..instead of increasing complexity in helper you can just use @Html.Raw() helper as i have shown in my answer.. – Kartikeya Khosla Aug 07 '14 at 12:56
  • 1
    @Exception `Html.Raw` will not help you correctly escape the HTML attributes. Try setting `alt` to something with a quote in it. For exmaple `here's a pretty picture`. You'll get invalid HTML with your code. Besides that I think the semantics make all the difference. Code in views should be as simple as possible, that's the whole point of having these HtmlHelpers in the first place. – Marnix van Valen Aug 07 '14 at 13:08