Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET dynamically insert code into head

Tags:

c#

asp.net

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?

like image 730
Kyle Avatar asked Dec 30 '09 19:12

Kyle


3 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");
like image 52
Eilon Avatar answered Nov 16 '22 16:11

Eilon


I realize that this is an old question, but this is another example.

Try This:

Page.Header.Controls.Add(
    new LiteralControl(
        "<script>alert('Literal Added to <Head>.');</script>"
    )
);

If you want to add the script at a particular index of the <head> you can use

AddAt(index, new LiteralControl(...)) where index 0 equals the top of the <head>

Also, you need to add runat="server" in your head tag e.g. <head id="head1" runat="server">

like image 27
nu everest Avatar answered Nov 16 '22 16:11

nu everest


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.

like image 9
Gabriel McAdams Avatar answered Nov 16 '22 17:11

Gabriel McAdams