I’m trying to get a good idea on how to modify certain parts of the page based on what page I’m looking at. I can set certain elements with the page’s controller but I’m thinking more about the global navigation menu’s (currently being rendered with a RenderAction in the application’s MasterPage) active states.
Like if I have some navigation links at the top of the screen (using SO’s as an example)
Questions | Tags | Users | …
If I’m in the “Questions” area or page then I want the Questions link to be active with a different color.
I don’t want to have to manage this on every page and plus I don’t want to be sending in values to my master page and then sending it through the RenderAction as I think that’d be messy. What I want is the Action to just know what area the rendered page is in and highlight the necessary elements.
The ViewMasterPage has a ViewContext property. The ViewContext contains the RouteData. The RouteData should have an entry for the name of the controller and current action, if they aren’t the default. You could use these in your logic on the master page to determine which navigation elements to highlight.
Similarly, if you used a partial view for the navigation, you would have access to the RouteData through the ViewContext property on the ViewUserControl.
EDIT: I don’t think it needs to be complicated.
In fact, I might even refactor it to an HTML extension to make it easier. Turns out that the helper already has a reference to the ViewContext so you don’t even need to determine the current controller in the view. Note that I’m only showing one signature, you can add other signatures to handle additional route data and html attributes (these would need to be merged) as needed.