asp.net-corelayoutmenusidenav

Show/Hide a sidebar menu in a _layout.cshtml file for an ASP.NET Core Web App (ver 6.0)


I have a in my _layout.cshtml file to show/hide a sidebar menu. I use javascript to modify the attributes to either show or hide the sidebar when the button is clicked. Everything works but it is not persistent. That is if the page reloads or the user goes to another page using the same _layout.cshtml the sidebar menu goes back to the default state (which is hidden).

CSS file

div.SideNav {
    width: 100px;
    min-width: 100px;
    display: none;
    vertical-align: top;
    background: #4B6C9E;

Javascript

<script>
    function openNav() {
        document.getElementById("SideNavID").style.display == "table-cell") 
    }
    function closeNav() {
        document.getElementById("SideNavID").style.display = "none";
    }
</script>

_layout.cshtml

<button onclick="openNav()">&nbsp;&#9776&nbsp;</button>
<button class="ButtonClose" onclick="closeNav()">&nbsp;&times;&nbsp;</button>

I was going to try and use a session variable to track and keep everything consistent. I tried several ways to catch the onclick event outside the javascript and in C# but can’t figure it out. Being in the _layout is causing me problems. I have thousands of pages that use the _layout so I can’t put anything in the code-behind for those pages. I was also looking at trying to set the session var in javascript. Is there a better way to manage or implement a sidebar menu


Solution

  • Instead of using session variable from the server, you can use client-side storage. You can use localstorage to persist the state between refreshes

    https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage