ASP.NET masterpages: how to insert markup in the head section inside the aspx?

splattne picture splattne · Feb 20, 2009 · Viewed 25.3k times · Source

I know I can access the head section of a page which uses a masterpage programmatically this way (in code behind):

This is only an example (I'd like to insert scripts and styles etc.):

this.Header.Title = "I just set the page's title";

Is there a simple way to do this in a declarative way on in the aspx file itself?

Sometimes it would be handy to insert a client script or a style declaration or a link to an external resource.

Answer

LukeH picture LukeH · Feb 20, 2009

You can do this by using content regions in the head, in exactly the same way as you would in the body of the page. eg, In your masterpage:

<head>
    <link type="text/css" rel="stylesheet" href="/styles/common1.css" />
    <script type="text/javascript" src="/scripts/common1.js"></script>
    <asp:contentplaceholder id="ExtraStylesAndScripts" runat="server" />
</head>

And then in the page itself just something like:

<asp:content contentplaceholderid="ExtraStylesAndScripts" runat="server">    
    <link type="text/css" rel="stylesheet" href="/styles/extra1.css" />
    <link type="text/css" rel="stylesheet" href="/styles/extra2.css" />
    <script type="text/javascript" src="/scripts/extra1.js"></script>
    <script type="text/javascript" src="/scripts/extra2.js"></script>
</asp:content>