views:

77

answers:

6

I want to find a place to put my Google Analytics code in my ASP.NET web application. I would like to place it somewhere once and not have to copy and paste the code into multiple files. Is there somewhere that I could inject it that I would only have to include it once and all pages would be effected? I am not using MasterPages unfortunately.

A: 

--- updated --

Add following class in your app_code


public class WebsitePageBase : System.Web.UI.Page
{
    public const string analyticsCode = "your script goes here..."
    protected void Page_Load(Object sender, e as EventArgs)
    {
       ClientScript.RegisterStartupScript(Me.GetType(),"__analytics_script",analyticsCode )
    }
}


and when you add a new aspx page you have to inherit from the new base class so for example you are adding default.aspx your back end class should look like:


public partial class _default : WebsitePageBase
{

}
lakhlaniprashant.blogspot.com
Have you read question to the end?
Restuta
A: 

You could put it into a page and then include this page everywhere you want to be check. But masterpage is the best for it.

ykatchou
+3  A: 

Create a base page which inherits from the Page class, and insert it into the head there. Then have all your other pages inherit from the base page :-)

IrishChieftain
+1  A: 

Create base page for all pages and add google analitics there. Then inherit each new page from this one.

e.g.

class PageWithGoogleAnalytics : Page
{
    //some actual code to add analytics
}

class MyCustomPage : PageWithGoogleAnalytics {}
Restuta
A: 

Another suggestion, and yes this is a massive hack, but you could write a HttpModule to automatically inject it into the page after the HTML has been generated by ASP.NET but before IIS sends the request down to the browser.

Note: I really wouldn't suggest this option, but it might be your only choice.

Kane
+2  A: 

You would either need to have a base page, or put a custom control on each page where you need the script.

In either of those, you can subscribe to the Init event, and then do the following:

protected override void OnInit(EventArgs e)
    {
        var myAnalyticsScript = @"<insert_analytics_script_here>";
        this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "analyticScript", myAnalyticsScript);
    }

If you choose a base page, you can control which pages the script appears on by not inheriting from the base page. If you choose a control, you do the same by not putting the control on a page.

Slavo