将页基中的代码添加到c#头文件中

本文关键字:文件 添加 代码 | 更新日期: 2023-09-27 18:12:49

我有以下代码在我的MasterPageBase.cs文件:

        protected override void OnLoad(EventArgs e)
    {
        string url = Request.Path;
        var page = _ContentPageRepository.GetContentPageByUrl(url, ConfigurationManager.GetSiteID());
        if (page != null)
        {
            PageBase.SetTitle(page.Title);
            PageBase.SetDescription(page.Description);
            PageBase.SetKeywords(page.Keywords);
        }
        else
        {
            this.ProcessSiteMap();
        }
        this.AddGACode(); 
        base.OnLoad(e); 
    }

我需要将this.AddGACode();添加到页面的头部部分,但是当我在运行解决方案时查看页面的源代码时,我看到这是将其添加到页面的主体部分。

我试过Page.Header.Controls.Add(AddGACode());,得到以下错误:The best overloaded method match has some invalid argumentscannot convert from 'void' to 'System.Web.UI.Control'

我怎么做才能把这段代码添加到头部?TIA

编辑:请求查看AddGACode方法:

        private void AddGACode()
    {
        var gaCode = SiteManager.GetSite().GoogleAnalyticsCode;
        if (!String.IsNullOrEmpty(gaCode) && Response.StatusCode == 200)
        {
            if (!ConfigurationManager.EnableUniversalGATracking)
            {
                ClientScriptManager cs = Page.ClientScript;
                StringBuilder csText = new StringBuilder();
                csText.Append("<script type='"text/javascript'">");
                csText.Append(String.Format("var _gaq = _gaq || []; _gaq.push(['_setAccount', '{0}']); ", gaCode));
                csText.Append("_gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })();");
                csText.Append("</script>");
                cs.RegisterClientScriptBlock(GetType(), "GACode", csText.ToString());
            }
            else
            {
                ClientScriptManager cs = Page.ClientScript;
                StringBuilder csText = new StringBuilder();
                csText.Append("<!-- Universal GA Code --><script type='"text/javascript'">");
                csText.Append(String.Concat("(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', '", gaCode,  " ', 'auto'); ga('send', 'pageview');"));
                csText.Append("</script>");
                cs.RegisterClientScriptBlock(GetType(), "GACode", csText.ToString());
            }
        }
    }
编辑:

这段代码在AddGACode方法中。页面的OnLoad中仍然有this.AddGACode();,似乎与此编辑复制了代码,但如果我从OnLoad中删除this.AddGACode();,这两个代码将消失

ClientScriptManager cs = Page.ClientScript;
StringBuilder csText = new StringBuilder();
csText.Append("<!-- Universal GA Code --><script type='"text/javascript'">");
csText.Append(String.Concat("(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', '", gaCode,  " ', 'auto'); ga('send', 'pageview');"));
csText.Append("</script>");
cs.RegisterClientScriptBlock(GetType(), "GACode", csText.ToString());
LiteralControl lc = new LiteralControl(csText.ToString());
Page.Header.Controls.Add(lc);

将页基中的代码添加到c#头文件中

这将脚本添加到head标签中:

        LiteralControl lt = new LiteralControl("<script type='text/javascript'>alert('test');</script>");
        Header.Controls.Add(lt);

LiteralControl lt = new LiteralControl(AddGACode());
Header.Controls.Add(lt);

private string AddGACode()
{
    var result = string.Empty;
    var gaCode = SiteManager.GetSite().GoogleAnalyticsCode;
    if (!String.IsNullOrEmpty(gaCode) && Response.StatusCode == 200)
    {
        StringBuilder csText = new StringBuilder();
        csText.Append("<script type='"text/javascript'">");
        if (!ConfigurationManager.EnableUniversalGATracking)
        {
            csText.Append(String.Format("var _gaq = _gaq || []; _gaq.push(['_setAccount', '{0}']); ", gaCode));
            csText.Append("_gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })();");
        }
        else
        {
            csText.Append(String.Concat("(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', '", gaCode,  " ', 'auto'); ga('send', 'pageview');"));
        }
        csText.Append("</script>");
        result = csText.ToString();
    }
    return result;
}

我会保留您的标记,在本例中是您的ga脚本,在主页本身。在head标签中添加两个字面值,gaGaqgaUniversal,然后使用您的逻辑来控制它们的可见性。

<head runat="server"><script type="text'javascript">
       <asp:Literal id="gaGaq" runat="server">
             <!-- Put you gaq code here-->
             <!-- Keep {0} as a place holder for gaqCode -->
             </script>
       </asp:Literal>
       <asp:Literal id="gaUniveral" runat="server">
            <script type="text'javascrtip">
            <!-- Put you universal code here-->
            <!-- Keep {0} as a place holder for gaqCode -->
            </script>
       </asp:Literal>
</head>
c#

private void AddGACode()
{
    var gaCode = SiteManager.GetSite().GoogleAnalyticsCode;
    if (!String.IsNullOrEmpty(gaCode) && Response.StatusCode == 200)
    {
        if(ConfigurationManager.EnableUniversalGATracking)
        {   
            //Set gaCode
            gaUniversal.Text = string.Fomat(gaUniveral.Text, gaCode);
        }
        else
        {  
            //Set gaCode             
            gaGaq.Text = string.Format(ga.Text, gaCode);
        }
        gaUniversal.Visible = ConfigurationManager.EnableUniversalGATracking;
        gaGaq.Visible = !ConfigurationManager.EnableUniversalGATracking;
    }
    else
    {
       //Hide Both literals if no gaCode
       gaUniversal.Visible = gaGaq.Visible = false;
    }
}

您还可以考虑将所有这些放入自定义控件中。如果你对这条路线感兴趣,我写了一篇关于gaq风格的谷歌分析的博客文章,这样我就可以把它放到我的许多asp.net网站上。该文章中的代码需要修改以满足您的需求,但应该足以让您开始。