Well I was on a development of one of the websites lately and I was using MVC 3 to create it. I have always liked when the menu bar highlights the current page. It is very easy to do in a website without master page which have separate body tag for each page, Only CSS is required for that, but when it comes to MVC 3 which has a layout page and only one body tag, the CSS trick just wont work.
There has been lots of blogs and discussions for doing this but I noticed they all need a lot of code or scripts to do that. I believe that doing something like this should not take more than 5-10 lines of code and should be mostly CSS. I was able to do it with this trick, I think it will be fairly a time saver for new MVC developers..
We want to achieve something like this:
Here is how my Controller looks like. Notice that I have added keys to ViewBag ie. ViewBag.CurrentPage and both Home and About methods initialize it to “home” and “about”.
We will use this to identify current page on our razor code.
This is how my body tag looks like
I am giving body a dynamic id, that id will be my ViewBag.CurrentPage value which means my body will have different id when i navigate to different page say Home or About.
and this is how my menu items looks like, nothing much special about it, just adding id attribute and value, Home link has id “home” and About link has id “about”
and finally the CSS
So now we have something equivalent of having multiple unique body id at one time for the browser. Whenever the anchor tag id and body tag id matches, it will override the current stylesheet with our defined new one [in the above picture]
So Simple isn’t it. Saves you a lot of coding as compared to other blog/discussions I have seen.
Please note that you have to take special care when you are doing some scripts that use your body tag id.
Other than that, you are all set to explore your style sheets skills to make a super cool menu bar.
Stay tuned we will be having more MVC 3 stuff comming up soon.