I have a solution which has both an ASP.NET Core 3.1 web application project as well as a Razor Client Library (RCL) project. I am trying write a view component which will be distributed with the Razor Client Library, but can be referenced from the ASP.NET Core web application.
I can successfully render this ViewComponent
when I call the InvokeAsync()
Tag Helper on the web application's _Layout.cshtml
:
@await Component.InvokeAsync("NavBar", new {})
But I want to make it so that the RCL is not dependent on a string name provided on the web application. Instead, I would like to call the ViewComponent
via an extension method like this:
@{ await Component.RenderMyViewComponentAsync(); }
To me, this way is more beneficial to whoever will use this shared RCL Library, as they don't need to specify the exact name of the ViewComponent
, and can rely on IntelliSense to complete the extension method.
I have created a helper class that takes the ViewComponent
object and simply calls its InvokeAsync()
method within an extension method:
public static class PartialHelper
{
public static async Task<IHtmlContent> RenderMyViewComponentAsync(this IViewComponentHelper vcHelper)
{
return await vcHelper.InvokeAsync("NavBar", new { });
}
}
And, of course, inside of NavBarViewComponent.cs
, I have implemented the InvokeAsync()
method:
public class NavBarViewComponent : ViewComponent
{
public async Task<IViewComponentResult> InvokeAsync()
{
return View();
}
}
Here's the problem, though: I'm not seeing my view render on the screen from the latter method, even though both ways of doing it will still hit my NavBarViewComponent.InvokeAsync()
.
From what I see, both ways of returning the ViewComponent
s are functionally equivalent and use the same methods, except @{ await Component.RenderMyViewComponentAsync(); }
goes through a helper function first.
I've tried debugging both ways, but to no avail. I am stuck!
Is there any way to achieve what I'm asking for here? If any clarification is needed, please ask.