How to add dinamically meta tag (title, description, keyword) to ASP.Net content page
The following example shows how to dynamically add meta tags (title, description, keywords) in the <head> an ASP.Net page.
Code:
using System;
using System.Web.UI;
using System.Web.UI.HtmlControls;
public partial class info : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string title = GetTitle();
string descriptionContent = GetDescription();
string keywordsContent = GetKeywords();
// Important! Overwrites the contents of the html tag <title>
// Set the title of the page
Page.Title = title;
// Set meta tag description
HtmlMeta htmlMetaDescription = new HtmlMeta();
htmlMetaDescription.Name = "description";
htmlMetaDescription.Content = descriptionContent;
Header.Controls.Add(htmlMetaDescription);
// Set meta tag keywords
HtmlMeta htmlMetaKeywords = new HtmlMeta();
htmlMetaKeywords.Name = "keywords";
htmlMetaKeywords.Content = keywordsContent;
Header.Controls.Add(htmlMetaKeywords);
}
/// <summary>
/// Retrieves the title of the page, e.g. from the database.
/// </summary>
/// <returns></returns>
private string GetTitle()
{
string t = "Commercial information of the company MdmSoft";
return t;
}
/// <summary>
/// Retrieves a description of the page, e.g. from the database.
/// </summary>
/// <returns></returns>
private string GetDescription()
{
string d = "The MdmSoft Company, offers advice on computer systems in Small and Medium Enterprises.";
d+= "Our web agency develops innovative websites.";
return d;
}
/// <summary>
/// Retrieves the keywords of the page, e.g. from the database.
/// </summary>
/// <returns></returns>
private string GetKeywords()
{
string k = "MdmSoft, computer systems, Small and Medium Enterprises, web agency, innovative websites";
return k;
}
}