ASP.NET dynamically insert code into head

Viewed 46062

I'm working inside of a Web User Control (.ascx) that is going to be included in a regular web form (.aspx), but I need to be able to dynamically insert code into the head of the document from the User Control. In my Coldfusion days <cfhtmlhead> would do the trick. Is there an equivalent of this in ASP.NET or a similar hack?

5 Answers

To add HTML markup you can do the following:

In your UserControl's code you can access Page.Header, which is itself a control. To that control you can then add new controls:

HtmlGenericControl newControl = new HtmlGenericControl("someTag");
newControl.Attributes["someAttr"] = "some value";
Page.Header.Controls.Add(newControl);

To add script markup you don't need access to the head tag at all since ASP.NET has helper methods on the ClientScriptManager that do the work for you:

Here are examples of some code you can also put in your user control's code:

// Register some inline script:
Page.ClientScript.RegisterClientScriptBlock(GetType(), "myAlertScript", "alert('hello!')", true);

// Register a script reference:
Page.ClientScript.RegisterClientScriptInclude(GetType(), "myLibraryScript", "~/Scripts/MyScriptLibrary.js");
this.Page.Header.Controls.Add

By doing this, you are adding controls to the head section. You can add any type of control. If you feel you need to add simple text (or you want to write the tags manually), then look into the LiteralControl class.

There's some guidance on using C# code to modify the page header here. It should work just fine from any server-side code that executes before the page load completes.

A simple e.g.

HtmlHead head = Page.Header;
HtmlTitle title = new HtmlTitle();
title.Text = "Test Page";
head.Controls.Add(title);

HTMLHead reference is in namespace

System.Web.UI.HtmlControls

Override the custom control's Load() method to add the controls or references you need into the page header while the parent .aspx page is being loaded server-side.

Related