views:

246

answers:

2

What are the advantages of extending HtmlHelper instead of creating a Custom Class.

f.e. <%= Html.Table(data) %> vs <%= CustomClass.Table(data) %>

+2  A: 

Because the HTML helper already defines a bunch of useful methods that you won't have in your custom class and most importantly you have access to the HttpContext. Of course you may say why not pass the HttpContext to my custom class, but then instead of <%= CustomClass.Table(data) %> you will have <%= CustomClass.Table(data, HttpContext) %> which IMHO is uglier.

Darin Dimitrov
+1  A: 

Like you suggest, the HtmlHelper class is just a .NET method that returns a string (generally consisting of HTML markup). So, technically, it is not really different than writing a custom class to do the same.

However, the key benefit of using a HtmlHelper over writing a custom class is it follows the conventional approach of rendering HTML controls into an ASP.NET MVC view. By using/extending HtmlHelpers, it is more obvious that your method intends to output HTML markup for a control. If you wrote a custom class to do the same, it would be less obvious that the intention is to render HTML controls, and other developers may not discover it as easily.

Many consider a key principle of ASP.NET MVC to be to favor * convention over configuration*. By using HtmlHelpers, you are staying inline with that principle.

Chris Melinn
I like this answer too, but I selected the one related to the HttpContext parameter. I would select both if possible.
gustavogb