将页面基础中的代码添加到标题C#

时间:2014-07-14 22:13:45

标签: c# asp.net head

我在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();添加到页面的head部分,但是当我在运行解决方案时查看页面的来源时,我看到这是将它添加到页面的主体部分页。

我尝试了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方法中。页面的this.AddGACode();中仍有OnLoad似乎与此修改重复了代码,但如果我从this.AddGACode(); OnLoad,则这两个代码都会消失>

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);

2 个答案:

答案 0 :(得分:1)

这会将脚本添加到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;
}

答案 1 :(得分:0)

我会在桅杆页面上保留您的标记,在这种情况下是您的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风格的谷歌分析编写了一个blog article,所以我可以将它放到我的许多asp.net网站上。该文章中的代码需要进行修改以满足您的需求,但应该足以引起您的注意。