我有一个解决方案,其中既有 ASP.NET Core 3.1 Web 应用程序项目又有 Razor 客户端库 (RCL) 项目。我正在尝试编写一个 View 组件,该组件将随 Razor 客户端库一起分发,但可以从 ASP.NET Core Web 应用程序中引用。
当我在 Web 应用程序的 _Layout.cshtml
上调用 InvokeAsync()
标记帮助程序时,我可以成功渲染此 ViewComponent
:
@await Component.InvokeAsync("NavBar", new {})
但我想让 RCL 不依赖于 Web 应用程序上提供的字符串名称。相反,我想通过这样的扩展方法调用ViewComponent
:
@{ await Component.RenderMyViewComponentAsync(); }
对我来说,这种方式对使用这个共享 RCL 库的人来说更有利,因为他们不需要指定 ViewComponent
的确切名称,并且可以依靠 IntelliSense 来完成扩展方法。
我创建了一个辅助类,它采用 ViewComponent
对象并在扩展方法中简单地调用其 InvokeAsync()
方法:
public static class PartialHelper
{
public static async Task<IHtmlContent> RenderMyViewComponentAsync(this IViewComponentHelper vcHelper)
{
return await vcHelper.InvokeAsync("NavBar", new { });
}
}
当然,在 NavBarViewComponent.cs
内部,我实现了 InvokeAsync()
方法:
public class NavBarViewComponent : ViewComponent
{
public async Task<IViewComponentResult> InvokeAsync()
{
return View();
}
}
但问题是:我没有看到后一种方法在屏幕上渲染我的 View ,尽管这两种方法仍然会影响我的 NavBarViewComponent.InvokeAsync()
。
据我所知,返回 ViewComponent 的两种方法在功能上是等效的,并且使用相同的方法,除了 @{ wait Component.RenderMyViewComponentAsync(); }
首先执行辅助函数。
我尝试过两种方式调试,但没有成功。我被困住了!
有什么办法可以实现我在这里所要求的吗?如果需要任何澄清,请询问。
最佳答案
扩展方法也有同样的问题,谢谢您的回答。
补充一点 - 不要使用字符串,而是使用泛型在编译时捕获错误:
await Component.InvokeAsync<NavBar>();
或直接从 Controller :
public IActionResult Index()
{
return ViewComponent(typeof(NavBar));
}
关于c# - 从 IViewComponentHelper 扩展方法中调用 Component.InvokeAsync(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60745777/