Search code examples
c#webformsmeta-tagsmeta

meta tags with c# code content don't render


For example- this is my meta tag:

<meta name="keywords" content="<%=eSeo.keyWords%>" />

It suppose to become-

<meta name="keywords" content="food,dogs,cats" />

and I can see through the page source in the browser that it stays:

<meta name="keywords" content="<%=eSeo.keyWords%>" />

As a string..

I tried to update the meta tag from the behind code, and it doesn't work as well:

protected override void OnPreRender(EventArgs e)
    {
        if (!IsPostBack)
        {
            HtmlHead pHtml = Page.Header;

            foreach (HtmlMeta metaTag in pHtml.Controls.OfType<HtmlMeta>())
            {
                if (metaTag.Name.Equals("keywords", StringComparison.CurrentCultureIgnoreCase))
                {
                    metaTag.Content = eSeo.keyWords;
                    break;
                }
            }
        }
        base.OnPreRender(e);
    }

Solution

  • What you need to do is give the meta tag an ID and runat="server" and use binding to set the value.

    For example:

    <meta ID="MetaKeywords" runat="server" name="keywords" content="<%#eSeo.keyWords%>" />
    

    and in code behind

    protected void Page_Init(object sender, EventArgs e)
    {
    MetaKeywords.DataBind();
    

    ....