I'm new with ASP.Net Core (3.0 in this case) and I´m trying to create a menu that is visible on all views of a WebApplication, is created dynamically and must be populated only once. Below i explain the steps and try outs i did to reach the goal needed (if required i can share the code I'm using).
This is what i did:
- In a simple way, using the "_Layout.cshtml" page, i created a static HTML menu and made all other views simply inherit that layout. So far, so good;
- Next challenge comes from the fact that the menu items are dynamically created after a User has logged-in, which i managed to overcome by setting a ModelView inside a controller (
HomeController.cs
withIndex
action in this case), and then delivering it to the view. For this case works OK, because the default page is~\Home\Index\
, problem is when i change to a different view with a different controller, the menu has to be rendered again, and so i have to replicate the code (a problem dealt create a BaseController and BaseModel based on this post along side theOnActionExecuted
to host the menu generating code) - Now, the biggest problem is the fact that i can only populate the menu once, after the user logs-in. Each time there is a redirect between different controllers/views (post-back of same controller/view works fine), the model is null inside the
OnActionExecuted
, I tried using ViewData, ViewBag, TemData, but all are null.
So, my question is, how to keep that specific data alive and shared, basically across all the views, and only gets populated once (after each user login) between redirects from different views? I have been reading around and found several solutions besides the one i did, but i did not found any that could keep data alive throughout the user session the way I need:
- ViewBag, ViewData and TempData
- Can the shared layout view have a controller in ASP.NET MVC?
- Pass data to layout that are common to all pages
To sum up, my flow at this moment, is like this:
- User Logged-in
- Redirect to default:
~\Home\Index
MenuModelView.cs
for the menu gets built andHomeController.cs
returns toIndex.cshtml
with the model attached to it.Index.cshtml
receives the populated ModelView and it uses_Layout.cshtml
- The
_Layout.cshtml
builds the HTML tags for the menu based on theMenuModelView.cs
data - User navigates to a different view and steps 3 to 5 are repeated from a specific controller/view