Giving Your MVC Views an Identity

One of the great CSS tips I got from Zen of CSS was to put an id on the body tag of your html pages.  This makes it really easy to use one CSS file for your entire site (a optimization trick) and allow you to target elements on specific page easily without creating a lot of unnecessary content wrappers or bogey class names. 

It is also very simple thing to do on MVC sites. Using the convention of Controller+Action give an easy identifier (if you’re using areas or something else you will need to tweak this a little).  This simple extension method does all the work for you.


public static class MasterPageExtensions
        public static string BuildPageIdentifier(this ViewMasterPage masterPage,  ViewContext context)

            return string.Format(“{0}-{1}”, context.RouteData.Values["controller"],context.RouteData.Values["action"]);

Now just add this to your MasterPage.


<body id=”<%= this.BuildPageIdentifier(this.ViewContext)%>“>

It will create html that looks like this.

<body id=”Resident-Edit”>

Now you can write CSS like this to target specific pages on your site.



#Resident-Edit #VolumeLevel { display:block; margin-bottom:.8em; }

This entry was posted in CSS, MVC. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • Hah! I’ve seen this before, but I always thought it was cheating or a hack. I’m glad that it’s not, but actually recommended!

  • That’s a great idea. This is also recommended in my favorite CSS book, CSS Mastery by Andy Budd.

    This can be especially useful for highlighting the current navigation tab automatically with CSS.

  • Aaron Jensen

    interesting idea.. my only concern is that now renaming controllers or actions requires a css change as well… a subtle coupling that I could see resulting in annoying regressions.

  • That’s a very good point.
    I will write up a watin test to verify and include it in the post

  • Paul

    @Ben Scheirman

    Do you have an example of how this could work?


  • Andreas
  • Excellent.
    I was going to work out how to do this myself, but now I can just copy you.

  • DO5N54 mrthzqsufyyq, [url=]ghbgxjrujsvv[/url], [link=]elsgfhvnyqcs[/link],