【问题标题】:Display ViewComponent in shared _Layout, only on certain pages在共享 _Layout 中显示 ViewComponent,仅在某些页面上
【发布时间】:2021-12-12 14:00:00
【问题描述】:

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

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

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

【问题讨论】:

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


    【解决方案1】:

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

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

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

    Index.cshtml

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

    在不希望视图组件显示的视图中跳过此代码块。

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

    _Layout.cshtml,你有:

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

    并且特定视图的标题在代码块中设置:

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

    在大多数情况下,ViewBagViewData 只有句法上的区别。有关它们的更多差异,请参阅this

    【讨论】:

      【解决方案2】:

      您可以将 VC 视图组件封装在部分视图中。

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

      何时调用局部视图,传递控制模型变量

      <partial name="./AuthenticatedLayout.cshtml" model="@HasAuthed" view-data="ViewData"/>
      

      有一个reference

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多