I am using ASP.NET Core 2.0 and Visual Studio 2017.
I want to create a Razor partial view to display the menu of our application. The menu is created dynamically as each user will only have menu items for which they have the necessary permissions (so the menu will be different for each user).
The problem I'm having is persisting the menu in the Razor partial view. There is no PageModel code-behind in a Razor partial view, so the problem I'm having is that the menu disappears when you click onto another page. I've persisted the menu in session storage, but I can't figure out how to load the menu from session storage into the Razor partial view.
I've tried loading the session storage menu into ViewData but this is wiped out when you click on another page.
How do I persist data in my Razor partial views?
Instead of using partial view, consider using a view component.
public class MenuComponent : ViewComponent
{
SomeDependency userDetails;
public MenuComponent(SomeDependency userDetails)
{
//store this userDetails data to extract profile info in Invoke method
this.userDetails = userDetails;
}
public IViewComponentResult Invoke()
{
//check for logged in user profile here and return appropriate view
return View(viewName,ModelObjectForView);
}
}
1.Create required menu views
Create the appropriate views for displaying menu for each role or use conditional rendering. Please note view for view components will be looked in to /Views/ControllerName/Components/ViewComponentName/ViewName.cshtml this location instead of /Views/ControllerName/ViewName.cshtml.
2.Define Layout Page
Now, since you need to display menu for all the pages user navigates to, you need to extract this view component in a layout page. Create a _Layout.cshthml file and make sure views that need to show menu item uses this layout page. In the _Layout.cshtml , you can now render the view component defined above by calling
@await Component.InvokeAsync(nameof(MenuComponent))
3.Using ViewComponent instead of PartialView
I am suggesting use of ViewComponent over PartialView in this case because ViewComponent will allow you to have its own model (RoleDetails for user in your case) in comparison to PartialView where you will have to pass some child data from view model and hence will have to keep that data in each of your view model. Otherwise , you can even use PartialView. The important thing here is layout page that will help you keep menu across all views presented to user.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With