Asp.net-mvc – When should we use Html Helpers, Razor Helpers or Partial Views

asp.net-mvcrazor

These three different features exist in the Razor view engine and can be used to achieve similar results. In the end all three of them just render pieces of HTML code, but the way to define and use them is fairly different. I know that:

Html Helpers are created as extension methods for the HtmlHelper class. They frequently use the TagBuilder class to generate some HTML and always should return an IHtmlString.

Razor Helpers (@helper methods) can be defined locally (in the same razor file) or globally (in the App_Code directory). They are small snippets of HTML code that can be reused exclusively in Razor files.

And finally, Partial Views are just regular view files that can be included in other view files using the @Html.Partial helper.

My question is:

Is there a specific scenario for each one of these features? Or it comes down to different flavors to achieve the same result?

Best Answer

HTML Helpers are for reusable components. e.g. WebGrid, Pager, etc. These are distributed as assemblies and have no dependency on Razor. Choose this if:

  • Functionality is truly reusable and applicable to any application
  • You don't want people to modify it, or want to version it

Partials Views are a way to split large views into smaller parts to keep things more manageable. They are also useful for reusability that is specific to your application. These are located by the view engine, so you can have the same partial defined in different places (e.g. Views/Shared), allowing you to customize per controller, area or display mode. Choose this if:

  • Functionality is application-specific
  • Want to customize per controller, area or display mode

Local Helpers are a way to execute the same template many times, without having to repeat yourself. You can also use it to break views into parts to avoid deep nesting, but keeping everything in the same file. Choose this if:

  • Functionality is view-specific

Application Helpers (in App_Code) are a mix between local helpers and HTML helpers. Choose this if:

  • Prefer Razor over TagBuilder
  • Don't mind distributing files instead of assemblies
  • Prefer type-safe method-call syntax instead of @Html.Partial(name)
Related Topic