Last week I talked about a situation where the previous programmer had placed the body tag inside the ContentPlaceholder in order to allow for a different body tag on the page.
Since this is a project that I am actively involved in, I’ve been thinking about the easiest way to “fix” the code so that we can use it.
To review, placing the body tag in the contentplaceholder makes the site much more difficult to maintain than it needs to be because you lose the ability to drag and drop controls into the designer. Even if you decide to not use the designer, you lose intellisense in the source view.
In thinking about this, I’ve come to the conclusion that the same goals could have been achieved any number of other ways that would not have had the same impact. Several that come to mind without thinking too hard are:
- Use separate master pages.
- Set the body tag attributes from the codebehind.
- Div tags in the contentplaceholder instead of the body tag
- Use multiple .NET Themes
Of the four, the first is probably the easiest to retrofit to the current code because the developers are not using themes in their code and because the same master page could be used across several pages. However, this would be a pain to maintain if there was a lot of UI code in the master page. Fortunately, there is not and what exists might be relegated to web user controls.
The second is probably the most preferred solution. By simply making the body tag a runat=”server” control you can then add any number of attributes to the body tag that you need from the codebehind.
In this sample, I exposed the body tag as a property of the master page.
MasterPage.Body.Attributes.Add("class", "class1 class2");
In the current case, the body tag has unique IDs per page, so this might be difficult to implement. But this is why I am a huge proponent of NOT using CSS rules in ASP.NET.
If you want to avoid the codebehind solution and you don’t want to use separate master pages, you might want to use DIV tags in place of the body tag. This will generally work well unless you are using the background color attribute of the body tag. In this case, you might need to use two DIV tags to accomplish what one BODY tag was doing. The outermost DIV tag will need to be styled with height and width of 100% and overflow: auto to make it scroll as needed.
The final solution is elegant but may have similar maintenance issues to those the master page solution has. You might consider using a common stylesheet that is loaded by the master page and only put page-specific CSS in your theme so that you can style the BODY tag or any of the items that depend on the style of the BODY tag in the theme, but all of your “regular” CSS would be called directly by the master page.