Skip to content
AtlanticBT Monogram Atlanticbt.com
October 16, 2009

Dynamic Body ID and Class properties on ASP.NET Master Pages

Master pages are a great feature of ASP.NET. However, they do have some drawbacks, one being they do not easily offer the flexibility of dynamic body ids and classes that our design team here needs.

Luckily a solution exists, and best of all it isn’t all that difficult to implement. The solution is built around the idea that child pages can access their master page, as well as any publicly exposed properties on the master. For example, in the Page_Load method of a child page, you can write:

MyMasterPage masterPage = Master as MyMasterPage; masterPage.Property = “property value”;

This is not ideal though, because we are now committed to never changing our child’s master page; if we do, it will break our build. The correct implementation of this concept is to create an interface that all of our master pages will implement, then use that in our child pages’ Page_Load method:

IMasterPage masterPage = Master as IMasterPage; masterPage.Property = “property value”;

We can still set our property this way, only now we can later change what master page we use, as long as the new one still implements the same interface. Good stuff. So good, that it puts us most of the way there towards dynamic body ids and classes.

To get these, we need a couple of properties on our interface:

public interface IMasterPage { String BodyId { get; set; } String BodyClass { get; set; } }

Then, in the code-behind file for our actual master page:

public partial class MasterPagesDefault : MasterPage, IMasterPage { private string _bodyId; private string _bodyClass; public string BodyId { get { return _bodyId; } set { _bodyId = value; } } public string BodyClass { get { return _bodyClass; } set { _bodyClass = value;} } }

Finally, in the master page’s body tag:

<body id=”<%= BodyId %>” class=”<%= BodyClass %>”>

Now, to set these dynamically, use the child page’s Page_Load method just like before:

IMasterPage masterPage = Master as IMasterPage; if (masterPage != null) { masterPage.BodyId = “index”; masterPage.BodyClass = “index two-col”; }

By using publicly accessible properties, we give child pages the ability to set values on their master page. With this, it is easy to create dynamic body classes and ids in .NET.

The Atlantic BT Manifesto

The Ultimate Guide To Planning A Complex Web Project

Partner With Us

Ready for modern web technology and a sharp, user-friendly design? We want to give you exactly that. Contact us to get started.

Contact
  • This field is for validation purposes and should be left unchanged.