Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/29.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将页面底部的代码添加到页眉C#_C#_Asp.net_Head - Fatal编程技术网

将页面底部的代码添加到页眉C#

将页面底部的代码添加到页眉C#,c#,asp.net,head,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)

我的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); 
    }
我需要
这个.AddGACode()
添加到页面的头部部分,但是当我在运行解决方案时查看页面的源代码时,我发现这是在将其添加到页面的主体部分

我尝试了
Page.Header.Controls.Add(AddGACode())
并获取以下错误:
最佳重载方法匹配有一些无效参数
无法从“void”转换为“System.Web.UI.Control”

我该怎么做才能将此代码添加到头部?短暂性脑缺血发作

编辑:请求查看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());
            }
        }
    }

这会将脚本添加到head标记中:

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

私有字符串AddGACode()
{
var result=string.Empty;
var gaCode=SiteManager.GetSite().GoogleAnalyticCode;
如果(!String.IsNullOrEmpty(gaCode)&&Response.StatusCode==200)
{
StringBuilder csText=新建StringBuilder();
csText.Append(“”);
如果(!ConfigurationManager.EnableUniversalGATracking)
{
追加(String.Format(“var_gaq=|u gaq | |[];_gaq.push”(['''u setAccount','{0}']);”,gaCode));
csText.Append(“_gaq.push”([''u 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(String.Concat(((函数(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]| function(){(i[r].q=i[r].q | |[])push(参数)},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)(谷歌分析)(www.js window.com),www.js.js.js.com'/'('create',','gaCode','auto');ga('send','pageview');”);
}
csText.Append(“”);
结果=csText.ToString();
}
返回结果;
}

我会将您的标记(在本例中是您的ga脚本)保留在主页本身上。在
head
标记中添加两个文本,
gaGaq
gaUniversal
,然后使用您的逻辑控制它们的可见性

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

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

Le让我们看看
AddGACode
。抱歉,我编辑了原始帖子。我想这会有所帮助:我不认为我能在细节方面提供帮助,但问题是
AddGACode
返回void,但您尝试将其结果分配给
Page.Header.Controls
。如果要将其分配给集合,您的方法应该返回一个控件n个控件。从技术上讲,它不是一个控件,只是一个被调用的方法。有没有其他方法可以确保谷歌分析代码进入页面的头部?当我添加这个时,它会开始向页面添加两次代码。我做错了什么?编辑了原始帖子。我唯一能想到的是使用断点来检查很多次你的代码都会通过这些行,为什么会这样。看起来是因为我把这个添加到了
AddGACode
方法中,并且仍然有
this.AddGACode()
在页面的
OnLoad
中调用,它被添加了两次。但是,当我从页面的
OnLoad
中删除代码时,两个代码都消失了。mmm删除脚本管理器在AddGACode中的调用,只需生成脚本并将其放入文本(用一个例子更新了我的答案)。感谢您喜欢我的答案,但在您自己的网站上复制被认为是不好的。请务必提及我的答案,但请不要复制。此代码由300多个网站共享,因此它需要保留在MasterPageBase中,否则我将有很多母版页要更新。:/但这是有用的信息!如果我找到一个网站,我可以请继续,我一定会的!@jlg这是因为我错过了母版页的基类部分!
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;
}
<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>
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;
    }
}