Search code examples
c#asp.net-coretag-helpers

Contextualizing in tag helper


What does it mean to contextualize a tag helper?

((IViewContextAware) _html).Contextualize(ViewContext);

I am trying to understand what the above code does?

What happens if I use the code above? and what not if I dont.

Reference


Solution

  • Contextualize() sets the ViewContext property of the IHtmlHelper where method is called on. Strictly speaking your not contextualizing the tag helper, just the HtmlHelper.

    The ViewContext encapsulates all information about the current view being executed as well as the currently executing action (as ViewContext derives from ActionContext). Most of the HtmlHelper methods depends on ViewContext being set: such as methods generating action links as it contains route data or for keeping state when rendering a form.

    MVC will automatically call Contextualize on the the HTML helper (in fact, on all IViewContextAware implementations) for when executing a regular Razor view. The HtmlHelper is not a default concept for tag helpers however. When you inject it through the constructor of the tag helper, it will create a new instance which is not "contextualized" with any view information. Therefore you have to call it manually.

    An exception will be thrown when a method which requires the ViewContext to be set is called.

    tl;dr: always call Contextualize when injecting IHtmlHelper in your tag helper or it won't function properly.