Search code examples
asp.netmaster-pagesstylesheetheadpage-title

asp.net derived master pages, page titles and dynamic css links


Not sure if the derived page is actually relevant to the problem here, but ran into an interesting gotcha on some code I'm working through at the moment.

I have a custom masterpage class, which derives from System.Web.UI.MasterPage so that it can be extended with additional useful properties.

The page that that uses this masterpage has a declaration at the top (note the Page Title being set).

<%@ Page Language="C#" MasterPageFile="~/MasterPages/Landing.master" AutoEventWireup="true" CodeFile="Index.aspx.cs" Inherits="Index" Title="Welcome to the site" %>

In addition, the master page has stylesheet references in the head which are pulled from a CDN that is defined in a config file.

<head id="Head1" runat="server">
    <link rel="stylesheet" type="text/css" href="<%= CDN %>/css/main.css" />
</head>

Now the example above obviously doesn't work, because the runat attribute in the head container means that the codeblock in the the link is static text, and renders as is, in the resulting html.

If I remove the runat attribute from head, the CDN works, but now I notice that the Title is no longer being set. If I debug, and try to access Page.Title in the Immediate Window, I get an exception:

// Using the Title property of Page requires a header control on the page. (e.g. <head runat="server" />).

So, is there a way to get the Page Title from the declaration, put my own title placeholder in the head and set it from the master page code-behind, or, is there a better way to dynamically set the CDN domain for the stylesheets? The only way I think I can do that is to build the entire html link tag(s) and append it to the header control, but I thought there might be a more elegant solution, so I'm asking here first.


Solution

  • Insofar as the CDN goes, we build a special Url.ResolveContentUrl() method that spoke with our configuration and pointed at the correct stylesheets (and any other static asset) depending on running mode, etc. So your dev and QA work locally then your production goes to the CDN with zero code changes.

    Also, you should put a content placeholder into the part of the masterpage. It is the only way to fly.