Joe Levi:
a cross-discipline, multi-dimensional problem solver who thinks outside the box – but within reality™

Dynamically writing your META tags using ASP.NET C#

Every year I have to go through our web sites and increment the copyright year to reflect the new year. This is time consuming and, frankly, the web site is run by a computer, so why can’t it take care of itself?
 
This is easy enough to do in a copyright line sitting somewhere on your displayed page, but somewhat obscure to get into the page’s meta data.
 
With that in mind I wrote a quick little method to handle writing the copyright meta tag for me. Afterwards I went back and made it generic to write any meta tag that you’d like.
 
Simply call the WriteMetaTag() method at Page_Load, passing the page control ("this"), the tag to be written (title, copyright, description, keywords, etc.), and the value of the tag.
 
   1:  protected void Page_Load(object sender, EventArgs e)
   2:  {
   3:      //Add copyright header with dynamic copyright year
   4:      WriteMetaTag(this, "copyright", "©, Copyright " + System.DateTime.Today.Year.ToString() + " Lifetime Products. All Rights Reserved.");
   5:  }
   6:   
   7:  /// <summary>
   8:  /// Static method that writes a given HtmlMeta tag with the supplied parameters
   9:  /// </summary>
  10:  /// <param name="ctrl">the control ("this" will suffice)</param>
  11:  /// <param name="tag">the meta-tag to be written (title, keyword, description, etc.)</param>
  12:  /// <param name="value">the value of the meta-tag (the page's title, a keyword list, the page's description, etc.)</param>
  13:  /// <returns>
  14:  /// A properly formatted HTML or xHTML meta-tag value-pair written into the page header
  15:  /// </returns>
  16:  public static void WriteMetaTag(Control ctrl, string tag, string value)
  17:  {
  18:      Page p = (Page)ctrl;
  19:      HtmlMeta m = new HtmlMeta();
  20:      m.Name = tag.ToLower();
  21:      m.Content = value;
  22:      p.Header.Controls.Add(m);
  23:  }

One less place you need to babysit the date.

Share

You may also like...

1 Response

  1. Joe Levi says:

    Also, don’t forget to add your “using System.Web.UI.HtmlControls;” statement, or fully qualify your HtmlMeta m = … line to reflect the right library.

    http://www.JoeLevi.com

Leave a Reply