2

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?

Amal K
  • 4,359
  • 2
  • 22
  • 44
JAmes
  • 261
  • 1
  • 5
  • 15

2 Answers2

2

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>
}

In the views/pages you want to show the view component from the layout, 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.

This is exactly also the way the default application template uses(as of .NET 5) to display a different title for each view.

In _Layout.cshtml, you have:

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

And the title for a specific view is set in a code block:

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

For the most part, ViewBag and ViewData have only syntactic differences. For more on their differences, see this.

Amal K
  • 4,359
  • 2
  • 22
  • 44
0

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

KennetsuR
  • 704
  • 8
  • 17