Home > Software engineering >  Display ViewComponent in shared _Layout, only on certain pages
Display ViewComponent in shared _Layout, only on certain pages

Time:10-27

I have this ViewComponent in my shared layout:

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

Is there a way to only have it render if the user is on a certain page, or exclude it from certain pages? Otherwise I'd just have to repeat it on every page that I need it to show?

CodePudding user response:

you can encapsulate the VC view component in partial views.

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

when to call the partial view, pass the controlling model variable

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

there is a reference

CodePudding user response:

There are multiple ways you could do this. One way would be, in your _Layout.cshtml decide on a ViewBag property name and check if it exists and is set to true. I've called it ShowVC:

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

The is operator takes care of both casting ShowVC to Boolean and checking if it is true in one step.

In the views/pages you want to show the view component, in a code block, set ShowVC to true. For instance, if you want to show it in a view called Index.cshtml, do this:

Index.cshtml:

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

Just skip this code block in the views where you do not want the view component to show.

  • Related