Highlighting current page in MVC 3 – Slick Trick.

Hi Everyone,

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:

34120847-menuhome
34120846-menuabout

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. 

 

34117774-controller

 

This is how my body tag looks like

34120058-body

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”

34120330-layout

and finally the CSS

34120381-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.

Cheers!

 


Posted

in

by

Comments

4 responses to “Highlighting current page in MVC 3 – Slick Trick.”

  1. sans Avatar
    sans

    This is cool..helped me to fix my header. thanks

  2. […] Original credit goes to Bhavin Surela – Highlighting current page in MVC 3 – Slick Trick. […]

  3. Appreciative Avatar
    Appreciative

    A truly slick trick in indeed! It’s really quite clever. I applaud your brilliance!

  4. dharma Avatar
    dharma

    Its really awesome , i was trying to do exactly the same for almost 2 days not able to find any right solution , but this helped me to resolve the issue . Thanks very much , appreciate your effort.