ASP.NET MVC @helper syntax vs Html Helper Extension methods

Piotr Czarnecki picture Piotr Czarnecki · Jul 23, 2013 · Viewed 17.1k times · Source

I need to create custom html helper method. As far as I know there are two ways:

  1. Use @helper razor syntax. http://weblogs.asp.net/scottgu/archive/2011/05/12/asp-net-mvc-3-and-the-helper-syntax-within-razor.aspx

  2. Create HtmlHelper extension method.

What solution is better and why? What are advantages and disadvantages?

I only read that in MVC 3 when @helper is created globally in seperate .cshtml file it's impossible to use other build-in html helpers. Don't know maybe in MVC 4 it is possisble.

Please help.

Answer

Bochu picture Bochu · Jan 6, 2015

One benefit to @helper is that, since the code is within the view, you can make changes to it without having to recompile your code. This lets you tweak the helper quickly and easily during development. I personally prefer to keep markup within views if possible for this very reason.

A related benefit of @helper is that your HTML will benefit from intellisense, while writing HTML in C# code gets no such benefit.

Additionally, if you are writing a helper that is not meant to be re-usable outside of a single view, then @helper makes it easier to make that clear. An HtmlHelper extension method would be confusing if only one view is intended to use it (unless you manage to put it in a class and in a namespace where only that one view would ever see the extension method).