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; }

Programming Basics: The for loop can do more than increment an integer