Keep menu toggle state after page reload

I saw some users need to keep left menu toggle state after page reload, the idea is quite simple, we need something to keep state, localStorage is a good candidate.

As usual, here is demo:


As you see in demo, when we hit menu toggle button on top left page, it will toggle sidebar-collapse class of body tag.
We need to store this state into localStorage and re-set it when page is reloaded.


We will need two helper methods to work with localStorage


Near bottom of _Layout.cshtml file, we will handle click event of toggle button and store state into storage with key IS_SIDEBAR_COLLAPSE


The rest is getting state from storage with key IS_SIDEBAR_COLLAPSE and toogle class sidebar-collapse for body tag

That’s it !


If you don’t want side menu push right panel everytime we hover mouse pointer on the menu then we can remove fixed class of body tag, the result will be something like this:

It’s not too bad I guess :)