Adding meta tag programmatically in C#

后端 未结 10 1156
渐次进展
渐次进展 2020-12-14 01:24

I\'m trying to programmatically add a . It is working fine when there is a Head element with runat = \"server\" in the

相关标签:
10条回答
  • 2020-12-14 01:46

    The best solution for this, which I successfully checked without any error or warning:

    The JavaScript code, which contains the <% ... %> code, was removed from the head section and placed in the body section.

    0 讨论(0)
  • 2020-12-14 01:52

    Many thanks to Awe for the solution! I have implemented this code in a (error404.ascx) ASP.NET User Control as follows:

    <%@ Control Language="C#"%>
    <script runat="server">
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.TrySkipIisCustomErrors = true;  //Suppress IIS7 custom errors
            Response.StatusCode = 404;
            SetRobotsHeaderMetadata();
        }
    
        private void SetRobotsHeaderMetadata()
        {
            HtmlMeta meta = new HtmlMeta();
            meta.Name = "robots";
            meta.Content = "noindex,follow";
            this.Page.Master.FindControl("cphPageMetaData").Controls.Add(meta);
        }
    </script>
    

    With the following masterpage:

    <%@ Master Language="C#" AutoEventWireup="true" Inherits="MyMaster" %>
    <script runat="server">
        ...
    </script>
    
    <!DOCTYPE html>
    <html lang="en-GB">
        <head>
            <title>Site title here</title>
    
            <asp:contentplaceholder runat="server" id="cphPageMetaData">
            </asp:contentplaceholder>
        </head>
    
        <body>
            ...
        </body>
    </html>
    
    0 讨论(0)
  • 2020-12-14 01:52

    I haven't tested it, but maybe you can add an <asp:Placeholder> inside the <head></head> tag and add the meta tags to this.

    0 讨论(0)
  • 2020-12-14 01:55

    OK, I tested the answer by veggerby, and it works perfectly:

    In the <header> section:

    <asp:PlaceHolder id="MetaPlaceHolder" runat="server" />
    

    Note that Visual Studio might show a warning on the PlaceHolder tag, because it is not recognised as a known element inside the header, but you can ignore this. It works.

    In the C# code:

    HtmlMeta meta = new HtmlMeta();
    meta.Name = "robots";
    meta.Content = "noindex,follow";
    MetaPlaceHolder.Controls.Add(meta);
    

    Alternatively (since you already have code blocks using <% %> in your header section), you can tag the meta directly and retrieve only the value from server side:

    <meta name="robots" content="<%=GetMetaRobotsValueFromDatabase()%>" />
    
    0 讨论(0)
提交回复
热议问题