在ASP.NET Core 1.1中引入了将视图组件用作标记帮助器。 (请参见“Invoking a view component as a Tag Helper”)。但是以下内容仅返回视图的Test for VC部分。似乎<vc:annual-orders>…</vc:annual-orders>
部分根本没有被调用。
Views \ Shared \ Components \ AnnualOrders \ Default.cshtml:
@{
Layout = "";
}
<div>Test for VC</div>
<div>
<vc:annual-orders>
</vc:annual-orders>
</div>
myProj \ ViewComponents \ AnnualOrdersViewComponent.cs:
public class AnnualOrdersViewComponent : ViewComponent
{
private readonly OrdersContext _context;
public AnnualOrdersViewComponent(OrdersContext context)
{
_context = context;
}
public async Task<IViewComponentResult> InvokeAsync()
{
var lastOrders = _context.Where(t => t.orderType == "new");
return View(await lastOrders);
}
}
注意:
我一直在为此苦苦挣扎,最终设法获得了标签助手,以使视图组件正常工作。我遇到的问题是标签助手在区域内的视图上不起作用。为了解决这个问题,我将/ Views目录中的_ViewImports.cshtml和_ViewStart.cshtml页面复制到了/ Areas // Views目录中,并且标签助手现在可以工作了,而VS在我的属性上赋予了intellisense。
不要忘记添加到_ViewStart.cshtml文件(其中是包含“视图组件”的程序集的名称:
@addTagHelper *, <AssemblyName>
这没有解决您的具体情况,但是密切相关,所以我认为我会把它留给需要听的人:
即使标签帮助程序已在例如根据@ alan-savage的回答,如果您未包含_ViewStart.cshtml
方法中的所有必需参数,则InvokeAsync()
将无法呈现。这看起来似乎是不言而喻的,但是由于它没有异常响应,也没有在Visual Studio中内置任何设计时验证,因此一开始可能会造成混淆。
因此,例如,如果您有:
public class AnnualOrdersViewComponent : ViewComponent {
public async Task<IViewComponentResult> InvokeAsync(string labelName) {
…
}
}
然后将您的标签助手称为:
<vc:annual-orders></vc:annual-orders>
您的代码将在没有警告的情况下进行编译,并且您的页面将毫无例外地运行-但是不会呈现视图组件,而是将其注入页面的源代码中。实际上,如果您将视图组件参数值设置为可选,甚至会发生这种情况,因为标记帮助程序语法不支持可选参数:
public class AnnualOrdersViewComponent : ViewComponent {
public async Task<IViewComponentResult> InvokeAsync(string labelName = null) {
…
}
}
很显然,在上述两个示例中,都可以通过例如:来解决此问题
<vc:annual-orders label-name="Contrived Example"></vc:annual-orders>
同样,这不能解决您的问题的详细信息,但是我认为遇到此问题的开发人员可能会遇到此线程,因此,如果标记帮助器已经正确安装,我想将此作为另一个故障排除步骤包括在内已注册。