Altering Master Page CSS Class on a page by page basis

The joys of a master page is that it gives uniformity across a website. If the customer wants to alter the look of a master page item on a specific page, it could get painful. Often the solution is the inclusion of additional conditional code in the master page. This solution is a spaghetti code approach.

 

A better solution is to tag the body of the master page with the name of the page, for example:

<body <%=PageSelector %>>

 

With this code behind:

public partial class Default : System.Web.UI.MasterPage
{
    public string PageSelector
    {
        get
        {
            string filename = Request.AppRelativeCurrentExecutionFilePath.Substring(
                Request.AppRelativeCurrentExecutionFilePath.LastIndexOf(@"/") + 1)
                .Replace(".", string.Empty)
                .Replace("aspx","Page");
            return String.Format("ID='{0}'", filename);
        }
    }

The result is that you will see

<body ID="SiteMapPage">

And you can now customize the CSS on a page by page basis (as needed)

 

  • H3 { } – used for all pages not customized
  • #SiteMapPage H3 { } – used for only SiteMap.Aspx

There is no need to muck with C# code to make the customer happy.

Adding a similar item around the content place holder, also is a good idea – it allows class name collisions to be easily resolved. i.e.

<div id="Content">
    <asp:ContentPlaceHolder ID="MainContent" runat="server" />
</div>
  • H2 { } used for the master page elements
  • #Content H2 {} used for the content elements

Comments

  1. If you're using .NET v4 you can do this now... (tags not allowed in comment)

    body runat="server" id="MasterPageBodyTag" clientidmode="Static" xmlns:sys="javascript:Sys"
    xmlns:dv="javascript:Sys.UI.DataView" xmlns:class="http://schemas.microsoft.com/aspnet/class"

    ... and in the master page codebehind...

    ///
    /// Gets or sets the body tag.
    ///
    /// The body tag.
    public HtmlGenericControl BodyTag
    {
    get
    {
    return this.MasterPageBodyTag;
    }
    set
    {
    this.MasterPageBodyTag = value;
    }
    }

    ...then in the individual pages...

    protected void Page_Load(object sender, EventArgs e)
    {
    Master.BodyTag.ID = "page1";
    }

    ReplyDelete
  2. Exactly what I was looking for. Great solution for those not using .NET 4.0.

    ReplyDelete

Post a Comment

Popular posts from this blog

Simple WP7 Mango App for Background Tasks, Toast, and Tiles: Code Explanation

Yet once more into the breech (of altered programming logic)

How to convert SVG data to a Png Image file Using InkScape