简体   繁体   中英

Modifying an exisiting meta tag

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

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);
    }

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.

Yes it is, do this:

HtmlHead pHtml = Page.Header;

instead. Creating a new HTML header won't exactly work well; instead just assigning the header will work much better. Just make sure an existing:

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

exists on the page, either in the master page or on that page.

If you want to remove meta tag in coding site then use following code

Dim meta4 As New HtmlMeta()

    meta4.Name = "AUTHOR"
    meta4.Content = "AUTHOR"
    Me.Page.Header.Controls.Remove(meta4)


    Dim meta5 As New HtmlMeta()

    meta5.Name = "DESCRIPTION"
    meta5.Content = "DESCRIPTION"
    Me.Page.Header.Controls.Remove(meta5)



    Dim meta6 As New HtmlMeta()

    meta6.Name = "KEYWORDS"
    meta6.Content = "KEYWORDS"
    Me.Page.Header.Controls.Remove(meta6)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM