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

Related Articles:

    Post Footer automatically generated by Add Post Footer Plugin for wordpress.

    This entry was posted in CSS, MVC. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
    • http://www.lostechies.com/members/chadmyers/default.aspx chadmyers

      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!

    • http://flux88.com Ben Scheirman

      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.

    • http://www.lostechies.com/members/jcteague/default.aspx jcteague

      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?

      Cheers!

    • Andreas
    • http://moleseyhill.com mat roberts

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

    • http://ervwmojfzscn.com/ jyefgcflxw

      DO5N54 mrthzqsufyyq, [url=http://ghbgxjrujsvv.com/]ghbgxjrujsvv[/url], [link=http://elsgfhvnyqcs.com/]elsgfhvnyqcs[/link], http://fwjgxgzttced.com/