So my boss told me that she wants to have the ‘active’ link in the navbar to be highlighted on my .net core project web app. I thought it would be super easy. It has not been super easy.

For any link in the navbar that uses controller actions, I’ve got it covered with this:
I know this is pretty ugly, but it’s a solution I found online that seemed to be the cleanest, and that I sort of understand. This works awesome for the controller/action calls. It looks something like this in my view:
But my problem is that I have a few pages that I used scaffolding to create. That means they are razor pages. One is a asp.identity scaffolding, so it is in areas/pages/identity/etc

The other is just a baseline razor page that I scaffolded in for some simple CRUD operations.
So, because these obviously don’t have controllers/actions associated with them, I went through the debugger to see what I would need to pass in in place of ‘routeAction’ and ‘routeController’ from the above method.

Turns out I need ‘area’ and ‘page’.
So I made a separate method for razor pages. Here it is, take note of the ‘routePage’ and ‘routeArea’ variables.
calling it like this:

I changed ‘RouteValueDictionary‘ to ‘RedirectToPageResult‘ as well. This actually works if i manually type in the URL. the nav item is highlighted. But If I actually CLICK the link, I get a ridiculous URL that looks like this: ‘localhost:5001/Identity/%2FAccount%2FRegister?PageName=%2FAccount%2FRegister&Permanent=False&PreserveMethod=False’

I read that the %2F was happening originally because I’m passing in the ‘/’ character, but I thought that the ‘RedirectToPageResult’ was supposed to properly handle that. I’m super lost right now. any help would be great. I feel like I’m very close…

So what happens if you put something like this in your _Layout.cshtml? I know it’s not C#, but could get the job done. Edit: Some of this would need slight changes for your use – you’re not using nav-tabs for starters – as I pulled that out of something I’m working on at the moment. Hopefully still of some use.

source