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.
-
why dont you pass Viewbag and if else logic – Sandip Bantawa Mar 11 '17 at 18:52
-
Can you demonstrate? That's pretty vague. – tocoolforscool Mar 11 '17 at 19:25
-
You can either set a `ViewBag.IsloggedIn=true` and then use that in the view. Or set `HttpContext.Items["LoggedIn"]=true`. – eadam Mar 12 '17 at 07:43
2 Answers
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.
![](../../users/profiles/-1.webp)
- 1
- 1
![](../../users/profiles/1733101.webp)
- 570
- 7
- 14
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>
![](../../users/profiles/5829437.webp)
- 372
- 1
- 6
- 23