C
C#2w ago
Bentopher

Dynamic header in _Layout

Hi there, I'm trying to get my head around how to dynamically change my nav header in the _layout.cshtml file. I want to add a new section to it if a user is in a specific zone. Then this section will use some data I pass in to create itself in the header. Does this mean that I need to pass in a model with the zone and data into the layout? Given that the layout is used on all pages will this be an issue if I don't pass in this model? I understand how passing models to different views works it's the fact that the layout is used in all views basically that has me confused on what way to do this.
5 Replies
Angius
Angius2w ago
That, I feel, is one of the few legit uses of ViewData I have
<title>@ViewData["Title"]</title>
<title>@ViewData["Title"]</title>
in the _Layout.cshtml, and set it with
@{
ViewData["Title"] = "FAQ";
ViewData["Description"] = "Frequently asked questions";
}
@{
ViewData["Title"] = "FAQ";
ViewData["Description"] = "Frequently asked questions";
}
in any given page Same for the description, as you can see
Bentopher
BentopherOP2w ago
So you think I should put my model in the ViewData and then cast it in the view when I want to use it. And I guess just have a check to see if there is a value in the ViewData before doing anything because it won't always be there in my case.
Angius
Angius2w ago
No, definitely do not put your model in the viewdata
greyfox
greyfox2w ago
Can also use a base viewmodel that all your other viewmodels inherit which contains shared properties that are set by the Index method of your controllers.
Bentopher
BentopherOP2w ago
I guess this might be the way to do it It's a tricky one for sure

Did you find this page helpful?