How to add meta tags dynamically to aspx page in c#


Introduction:

           Here I will explain how to add meta tags to a web page dynamically in c# .

Description: 

         
            In Previous posts I explained How to create Facebook App Id for website .Now i will explain how to add meta tags dynamically to .aspx page in c#. It will be helpful while sharing dynamic content  on Facebook .

Aspx Page

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
</head>
<body>
<form id="form1" runat="server">
<div>
<b> Meta Tags Example </b>
</div>
</form>
</body>
</html>


C# Code

In the page load event place the below code to add meta tags dynamically by using namespace System.Web.UI.HtmlControls

   protected void Page_Load(object sender, EventArgs e)
    {
        string fbAppID="445363636336363";
        string strTitle="Share title on facebook";
        string strImg1="http://localhost:6025/Demo/image.jpg";
        string strDesc="Description to share on facebook";
             
        HtmlMeta appId = new HtmlMeta();
        appId.Attributes.Add("property", "fb:app_id");
        appId.Content = fbAppID;
        this.Header.Controls.Add(appId);

        HtmlMeta tag = new HtmlMeta();
        tag.Attributes.Add("property", "og:title");
        tag.Content = strTitle;
        this.Header.Controls.Add(tag);

        HtmlMeta tagimg1 = new HtmlMeta();
        tagimg1.Attributes.Add("property", "og:image");
        tagimg1.Content = strImg1;
        this.Header.Controls.Add(tagimg1);
               
        HtmlMeta tagDesc = new HtmlMeta();
        tagDesc.Attributes.Add("property", "og:description");
        tagDesc.Content = strDesc;
        this.Header.Controls.Add(tagDesc);
    }

If you want to see output run above code snippet, after rendering the page Right click on your page and select view source in that check for Facebook app id, description, image and description meta tags that would be like this.


1 comment: Leave Your Comments

+