I am calling "TopNav" partial from within Layout master view.
I want TopNav view to be strongly typed and the model to be created within TopNavController.
Is there any way to render the action of a specific controller from within the master view? So in this case I need to render TopNav action of TopNavController in the Layout.
So far I can only use eg. @Html.Partial("TopNav") or @Html.RenderPartial("TopNav") with option to pass the model but I need to instantiate the model within the controller.
There used to be Html.Action("Action", "Controller") helper in previous versions but it doesn't seem to be available any more in .NET Core.
There's a good explanation of why
@Html.Action(..)was removed in a GitHub issue here: Why was @Html.Action removed?.Given that advice, it's clear that the recommendation for your example would be to create a View Component, which would be named
TopNavViewComponentby convention.ViewComponents/TopNavViewComponent.cs
The call to
Viewlooks for aDefault.cshtmlRazor file in a known location. Here's an example of what that file would look like (its expected location is in bold):Shared/Components/TopNav/Default.cshtml
To use this new View Component, add the following into your
Layoutview, wherever you want the output to be rendered:Shared/_Layout.cshtml
That should be enough to get you started with View Components. A couple of other useful things to know are:
InvokeAsync.I won't go into those two features here as it's all covered in the documentation and is outside of the scope of this question.