Adding meta tag programmatically in C#

后端 未结 10 1155
渐次进展
渐次进展 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:28

    You could define your meta tag as a static string like so:

    Private Shared MetaLanguage As String =
        String.Format("<meta http-equiv=""Content-Language"" content=""{0}""/>", CultureInfo.CurrentUICulture.TwoLetterISOLanguageName)
    

    Then place them in your head like so:

    <head runat="server">
        <%=MetaLanguage%>
    </head>
    

    This allow you to use any meta tag values and is easy to read and customize. Note: The use of the Shared keyword (static) helps improve performance.

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

    Or you could just put your meta-tag in the header, with an ID and a runat="server"... then in the code behind say

    myMetaTag.Content = "noindex,follow";
    

    or

    myMetaTag.Visible = false;
    

    or whatever you'd like.

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

    I think this is the best approach:

    this.Page.Header.Controls.Add(new LiteralControl(@"<meta ... />"));
    

    Enjoy!

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

    MetaDescription = "Your meta description goes here"; MetaKeywords = "Keyword1,Keyword2,Keyword3";

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

    OK... I actually only use C#... Or HTML into C#. I never use codebehind, designer or webcontrols in the file aspx... So I program everything from classes... And dynamically.

    Result:

    HtmlMeta meta = new HtmlMeta();
    meta.Name = "robots";
    `meta.Content = "Here is what you want";`
    var page=HttpContext.Current.Handler as Page;
    page.Header.Controls.Add(meta);
    
    0 讨论(0)
  • 2020-12-14 01:44

    Try moving whatever it is that you are doing in the <% .... %> to the code-behind. If you are using the script to add content into the page, you can replace it with an asp:Literal control and then set the value you were previously calculating in the script block to the code-behind and set Literal.Text to that value.

    0 讨论(0)
提交回复
热议问题