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?
Tag Helpers are attached to HTML elements inside your Razor views and can help you write markup that is both cleaner and easier to read than the traditional HTML Helpers. HTML Helpers, on the other hand, are invoked as methods that are mixed with HTML inside your Razor views.
Partial views are an effective way to: Break up large markup files into smaller components. In a large, complex markup file composed of several logical pieces, there's an advantage to working with each piece isolated into a partial view.
Strongly Typed HTML Helpers These helpers are used to render the most common types of HTML elements in strongly typed view like as HTML text boxes, checkboxes etc. The HTML elements are created based on model properties.
It binds the model object to HTML controls to display the value of model properties into those controls and also assigns the value of the controls to the model properties while submitting a web form. So always use the HtmlHelper class in razor view instead of writing HTML tags manually.
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:
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:
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:
Application Helpers (in App_Code) are a mix between local helpers and HTML helpers. Choose this if:
@Html.Partial(name)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With