How to access ViewContext from helper / service @injected via ViewImports

I am writing a helper class and _ViewImports into _ViewImports with

 @inject HtmlHelperInject.TestHelper TestHelper 

And register with Startup.ConfigureServices using

 services.AddTransient<TestHelper>(); 

How can I get the ViewContext in this helper class? I tried to inject through the controller - it does not work, through the [ViewContext] attribute on the property - it does not work.

+5
source share
1 answer

As of now (beta8) the way to do this is to implement ... wait for it ... ICanHasViewContext . This interface adds the following contract:

 void Contextualize(ViewContext viewContext); 

When you enter your custom utility, MVC calls Contextualize and goes to the current ViewContext . Note. This mechanism is likely to change in future releases. If not, the name will definitely be :)

Hope this helps!

+7
source

Source: https://habr.com/ru/post/1232736/


All Articles