0

I'm writing an application and I've implemented user log in functionality using cookie middleware. My share _Layout view has a navigation bar with links to "Register", "Login", and "Logout". The problem is that both "Login" and "Logout" appear on the navigation bar at all times whether one is logged in or not, so I need to be able to access the html elements in the shared view page from my controller to hide the "Login" button when one is logged in, and hide the "Logout" button when one ISN'T logged in.

tocoolforscool
  • 372
  • 1
  • 6
  • 23

2 Answers2

1

I need to be able to access the html elements in the shared view page from my controller

That's not how you do things in MVC. In MVC, the controller passes statically typed or dynamic (the viewbag) data to the view. Then the view uses this data to build whatever HTML it wants to.

First option would be for your layout menu (in the _layout view) to use a couple of properties from the viewbag like IsAuthenticated, UserName. You would then have to set these viewbag properties on each and every action, which is not very convenient.

Second option, register on application startup a global filter that will apply to all your controllers actions. Make the filter set viewbag properties IsAuthenticated, UserName on each and every request, based on the authentication status. As in the first option, your layout will then use these viewbag properties to build the menu. Much more clean and convenient.

How to register a global filter in ASP.NET Core

How to set viewbag properties from a filter

Community
  • 1
  • 1
Pierre Murasso
  • 570
  • 7
  • 14
0

Instead of manipulating the _Layout page directly, I created a _LoginPartial identical to the one that is generated if you select "Individual User Account Authentication" when creating the app.

_LoginPartial.cshtml:

@if (Context.User.Identity.IsAuthenticated)
{
    <ul class="nav navbar-nav navbar-right">
        <li>
            <a asp-area="" asp-controller="User" asp-action="Logout">Logout</a>
        </li>
    </ul>
}
else
{
    <ul class="nav navbar-nav navbar-right">
        <li><a asp-area="" asp-controller="User" asp-action="Register">Register</a></li>
        <li><a asp-area="" asp-controller="User" asp-action="Login">Log in</a></li>
    </ul>
}

Then I rendered the partial view inside the navbar of _Layout.cshtml:

<nav class="navbar  navbar-fixed-top">
        <div class="container">
            <div class="collapse navbar-collapse" id="navigation-index">
                <ul class="nav navbar-nav navbar-right">
                @await Html.PartialAsync("_LoginPartial")
                </ul>
            </div>
        </div>
    </nav>
tocoolforscool
  • 372
  • 1
  • 6
  • 23