Setting HTML tag attributes programmatically in ASP.NET Web Form


I was responding to a post on how to set the value of the xml:lang attribute of the html tag in an ASP.NET Web Forum. I knew from previous work with the head element that you can manipulate these, so I did a little test. Here is what you need to do, to get it working:

  1. Add an id attribute to the html opening tag, say id=”htmlMain”.
  2. Add the runat attribute to the html opening tag, runat=”server”.
  3. Declare a variable of type System.Web.UI.HtmlControls.HtmlGenericControl, named htmlTag.
  4. Assign htmlMain to htmlTag.
  5. Set the existing attribute or add a new attribute and value.


Markup:

<html id="htmlMain" runat="server">

Code for setting existing attribute:

HtmlGenericControl html = htmlMain;
html.Attributes["xml:lang"] = "da";

Code for setting new attribute:

HtmlGenericControl html = htmlMain;
html.Attributes.Add("xml:lang", "da");

It seems that both methods works, whether or not you have an existing attribute of the supplied name, so…

Advertisements