user710502
user710502

Reputation: 11471

How to add a script after the header tag dynamically

I would like to add a literal dynamically on a page but right after the </head> and before the <body>. How can i find this section programatically and add a literal dynamically ? So basically the page would end up looking like this:

<head>
</head>
<LITERAL HERE>
<body>
</body>

I sort of saw how to find the head tag but I do not know how to tell it to add the literal right after it closes and before the body. (This is for the Bing Ad Center tracking code as they suggest to put it there). But it needs to be dynamic because we will not always add tracking every time the user arrives to this page but only depending on certain cases.

Thank you

Upvotes: 3

Views: 1343

Answers (2)

rs.
rs.

Reputation: 27427

You can use literal control and bind text in page load event

<head>
    <asp:Literal ID="literal1" runat="server"></asp:Literal>
    <title></title>
</head>

C#

protected void Page_Load(object sender, EventArgs e)
{
    if(condition)
    {
      literal1.Text = "html or script tag";
    }
}

Upvotes: 0

Chris
Chris

Reputation: 370

You can use delimiters to insert the contents of a String directly into your page.

<head runat="server">
    <title></title>
</head>
<%= TrackingString %>
<body>
</body>

Make sure you have this string declared globally on the page that is referencing it, and as you manipulate this string on the page, it will be written to the page as text and parsed as HTML:

public partial class Default : System.Web.UI.Page
{
    public string TrackingString;

    protected void Page_Load(object sender, EventArgs e)
    {
        TrackingString = "<YourHtmlTag></YourHtmlTag>";
    }
}

In those cases where you do not want to track the user, simply set the string to String.Empty or to "" and nothing will be written to the HTML.

Upvotes: 3

Related Questions