Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying an exisiting meta tag

Tags:

c#

asp.net

I have this code to remove an existing meta tag to which i dont have access because it is in the solution dll it comes with but basically, I want to remove the meta tag content it comes with to our company content. The problem is that it is not finding the meta tag and I think is because of the way I am setting the htmlHead = Page.Header; I think i am missing something there.. but not sure.. This code is in a virtual Page_Load in a Base class.

    HtmlHead pHtml = Page.Header;

    for (int i = pHtml.Controls.Count - 1; i >= 0; i--)
    {
        if (pHtml.Controls[i] is HtmlMeta)
        {
            pMeta thisMetaTag = (HtmlMeta)pHtml.Controls[i];

            if (thisMetaTag.Name == mName)
            {
                pHtml.Controls.RemoveAt(i);
            }
        }
    }

I am not sure if i am giving the correct rederence to the header since this is in a virtual Page_Load in a Base class. Also most of this code was taken from (99%) from here Code for meta tag removal and replacement

Any help would be much appreciated

like image 275
user710502 Avatar asked Dec 08 '11 18:12

user710502


People also ask

Where do I edit meta tags in WordPress?

Click on Pages or Posts depending which you need to edit. Click the edit under the page or post title. Scroll down to the Yoast SEO section. Click the Edit snippet button.

Does changing meta description affect SEO?

Do Meta Descriptions Affect SEO? The short answer is no, they don't technically impact SEO. However, they are an important part of your SEO strategy as they are one of the first things searchers see when they encounter one of your pages.


2 Answers

It could be an issue with the order the events occur. I created a new page in ASP.NET

 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="FormMail.WebForm1" %>
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 <html xmlns="http://www.w3.org/1999/xhtml" >
 <head runat="server">
     <title>Untitled Page</title>
     <meta http-equiv="keyword" name="testy" content="default content" />
 </head>
 <body>
     <form id="form1" runat="server">
     <div>

     </div>
     </form>
 </body>
 </html>

I then used:

    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            string mName = "testy";

            HtmlHead pHtml = Page.Header;

            foreach (HtmlMeta metaTag in pHtml.Controls.OfType<HtmlMeta>())
            {
                if (metaTag.Name.Equals(mName, StringComparison.CurrentCultureIgnoreCase))
                {
                    metaTag.Content = "Yeah!";
                    break; //You could keep looping to find other controls with the same name, but I'm exiting the loop
                }
            }


            //for (int i = pHtml.Controls.Count - 1; i >= 0; i--)
            //{
            //    if (pHtml.Controls[i] is HtmlMeta)
            //    {
            //        HtmlMeta thisMetaTag = (HtmlMeta)pHtml.Controls[i];
            //        if (thisMetaTag.Name == mName)
            //        {
            //            thisMetaTag.Content = "Yeah!";
            //           // pHtml.Controls.RemoveAt(i);
            //        }
            //    }
            //} 

        }

    }

When I view the source, I see that the content of the meta tag was modified. Now, you're issue could be that at the time of looping, the control doesn't exist (wasn't added yet) and you're adding it, and then the built in code is adding it.

EDIT - Suggesting moving code to PreRender incase controls are added after load but before rendering

    protected override void OnPreRender(EventArgs e)
    {
        if (!IsPostBack)
        {
            string mName = "testy";

            HtmlHead pHtml = Page.Header;

            foreach (HtmlMeta metaTag in pHtml.Controls.OfType<HtmlMeta>())
            {
                if (metaTag.Name.Equals(mName, StringComparison.CurrentCultureIgnoreCase))
                {
                    metaTag.Content = "Yeah!";
                    break;
                }
            }
        }
        base.OnPreRender(e);
    }
like image 140
Nick Bork Avatar answered Sep 19 '22 10:09

Nick Bork


Though this is a old thread, I thought to share a LINQ based approach to select the HtmlMeta control from the Page controls collection:

HtmlMeta htmlMetaCtrl = (from ctrls in page.Header.Controls.OfType<HtmlMeta>()
                                     where ctrls.Name.Equals("keywords", StringComparison.CurrentCultureIgnoreCase)
                                     select ctrls).FirstOrDefault();
            if (htmlMetaCtrl != null)
                htmlMetaCtrl.Content = metaContent;

The following generic fuction can be used for changing the meta tags dynamically:

    public class WebUtils
{
    public static void SetPageMeta(string metaName, string metaContent, HttpContext httpContext = null)
    {
        if (string.IsNullOrWhiteSpace(metaName))
            return;

        if (metaContent == null)
            throw new Exception("Dynamic Meta tag content can not be null. Pl pass a valid meta tag content");

        if (httpContext == null)
            httpContext = HttpContext.Current;

        Page page = httpContext.Handler as Page;
        if (page != null)
        {
            HtmlMeta htmlMetaCtrl = (from ctrls in page.Header.Controls.OfType<HtmlMeta>()
                                     where ctrls.Name.Equals(metaName, StringComparison.CurrentCultureIgnoreCase)
                                     select ctrls).FirstOrDefault();
            if (htmlMetaCtrl != null)
                page.Header.Controls.Remove(htmlMetaCtrl);

            htmlMetaCtrl = new HtmlMeta();
            htmlMetaCtrl.HttpEquiv = metaName;
            htmlMetaCtrl.Name = metaName;
            htmlMetaCtrl.Content = metaContent;
            page.Header.Controls.Add(htmlMetaCtrl);
        }
        else
        {
            throw new Exception("Web page handler context could not be obtained");
        }
    }
}

This can be called from OnPreRender from the User Controls (ascx controls) or Page_PreRender from the Page (aspx):

        protected override void OnPreRender(EventArgs e)
    {
        if (!IsPostBack)
        {
    WebUtils.SetPageMeta("keywords", "Your keyword, keyword2, keyword3");
    WebUtils.SetPageMeta("description", "Your page description goes here...");
        }
        base.OnPreRender(e);
    }

Hope this helps someone.

like image 37
Diwakar Padmaraja Avatar answered Sep 21 '22 10:09

Diwakar Padmaraja