InfiniTec - Henning Krauses Blog

Don't adjust your mind - it's reality that is malfunctioning

Programmatically set the value of META-Tags with ASP.NET and C#

Affected products

  • .NET Framework 1.0
  • .NET Framework 1.1

Summary

This article explains, how to set the attributes of a META-Tag in an ASP.NET website.

Description

Since there is no META-Tag server control within the .NET framework, and the META tags are in the <head> section, thus outside of the <form> section, it is a little bit tricky to access these tags.

Solution

  1. First, create the desired Tag. In this article, a METAREFESH tag will be created. So open the ASP.NET page and insert the following line into the <head> section:
    <meta id="metaRefresh" runat="Server"/>
  2. Now, open the codebehind file, and add the following variable declaration on the class level:
    protected System.Web.UI.HtmlControls.HtmlControl metaRefresh
  3. Note, that the id in the ASP.NET file and the name of the variable must be identically.
  4. In The Page_Load event, add the following code:
    metaRefresh.Attributes["HTTP-EQUIV"] = "refresh";
    metaRefresh.Attributes["content"] = "3;URL=" + myUrl
  5. This code will cause the browser to do a METAREFRESH after 3 seconds. The user will then be redirected to the url specified in the myUrl variable.

Other informations

If you are using WebUserControls and want to access the META tags from within these controls, you should store the desired values in the session object and put the above code into a PreRender event handler. This handler is called after all controls have been loaded. You can then take the values from the Session object and put tehm into the meta tag.

Posted by Henning Krause on Friday, December 31, 2004 1:50 PM, last modified on Tuesday, July 26, 2011 9:57 PM
Permalink | Post RSSRSS comment feed