Add class attribute to body element with ASP.NET web forms and Master Pages

Posted on August 27, 2009 by Frederik Vig in ASP.NET, Code Snippet

Often I have to add a class to the HTML body element. This is a little code snippet that allows you to easily do this.

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site1.master.cs" Inherits="WebApplication1.Site1" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body runat="server" id="BodyTag">
    <form id="form1" runat="server">
    ...
    </form>
</body>
</html>

Add the public property BodyClass.

public string BodyClass
{
    set
    {
        BodyTag.Attributes.Add("class", value);
    }
}

Then in your .aspx, you need to make the Master Page strongly typed by adding MasterType (you can also manually cast it to the right type).

<%@ MasterType VirtualPath="~/Site1.Master" %>

You’ll now have access to the Master Pages BodyClass property.

Master.BodyClass = "home";
 
// Or by manually casting it
((Site1)Master).BodyClass = "home";
...
<body id="ctl00_BodyTag" class="home">
...

Related Posts: