c# - 在共享_Layout中显示ViewComponent,仅在某些页面上

标签 c# asp.net-core .net-core asp.net-core-mvc asp.net-core-viewcomponent

我的共享布局中有这个 ViewComponent:

@if (User.Identity.IsAuthenticated)
{
    <vc:room></vc:room>
}

是否有办法仅在用户位于某个页面时才呈现它,或者将其从某些页面中排除?否则我只需要在需要显示的每个页面上重复它?

最佳答案

有多种方法可以做到这一点。 一种方法是,在您的 _Layout.cshtml 中决定 ViewBag 属性名称,并检查它是否存在并设置为 true。我将其命名为 ShowVC:

@if (User.Identity.IsAuthenticated && ViewBag.ShowVC is true)
{
   <vc:room></vc:room>
}

在您想要显示布局中的 View 组件的 View /页面中,在代码块中,将 ShowVC 设置为 true。例如,如果您想在名为 Index.cshtml 的 View 中显示它,请执行以下操作:

Index.cshtml:

@model ModelClassName
@{
   ViewBag.ShowVC = true;
}

只需在您不希望显示 View 组件的 View 中跳过此代码块即可。

这也是默认应用程序模板(从 .NET 5 开始)为每个 View 显示不同标题的方式。

_Layout.cshtml中,您有:

<title>@ViewData["Title"] - AppName</title>

特定 View 的标题是在代码块中设置的:

@model ModelClass
@{
    ViewData["Title"] = "Title for the view"
}

在大多数情况下,ViewBagViewData 仅存在语法差异。有关其差异的更多信息,请参阅 this .

关于c# - 在共享_Layout中显示ViewComponent,仅在某些页面上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69735920/

相关文章:

c# - 命令模式和 OnPaint 事件问题

c# - XAML 中的 MergedDictionaries 重写为代码

azure - Azure 可以编译 TypeScript 并执行 Gulp 任务吗?

c# - 在 .NET Core 中获取类的公共(public)属性

.net - 如何将多个 .NET Core 程序集合并为一个(.dll/.exe)?

c# - []、get_Item() 和 Item[] 之间的 Excel Interop 区别

c# 从邮件中查找邮件

asp.net - 将asp.net core应用程序部署到azure后出错

c# - .net core 2 with ef core migrations with docker in development

c# - 无法在asp.net core 2.0 Web App中实现功能文件夹