posted on Thursday, August 19, 2004 11:06 AM by anoras

Its code-behind, not design-behind

During the last couple of weeks I’ve seen many blog posts about altering HTML elements programmatically in ASP.NET pages. To make any HTML element available in the code-behind class, just set the value of the element’s runat attribute to “server” and provide an identifier.

<HEAD id=”HeadHtmlElement” runat=”Server”>

To access the HEAD element in the code-behind class simply declare a class member of HtmlGenericControl with the same name as the identifier.

public class MyPage : System.Web.UI.Page {
      protected HtmlGenericControl HeadHtmlElement;
}

Making the HEAD element available as a class member makes it possible to, for example, programmatically add metadata to the page.

private void Page_Load(object sender, System.EventArgs e) { 
      HtmlGenericControl metadata=new HtmlGenericControl("meta"); 
      metadata.Attributes.Add("name","pragma"); 
      metadata.Attributes.Add("content","no-cache"); 
      HeadHtmlElement.Controls.Add(metadata);
}

Note that ASP.NET 2.0 has a Page.Header.Metadata collection which enables you to add metadata to the page.

Making the head of a page available for metadata injection is an acceptable. However, it would be much more elegant to use an HttpModule to inject the metadata into the pages.

Many of the blog posts I’ve seen have turned the code-behind class into a “design-behind” class moving the HTML into the class by setting the InnerText  property of the TITLE elements e.g. in code. A much better way to do this is to use the ASP.NET page as intended.

Do this:

<TITLE><%# GetResourceString(“PageTitle”) %></TITLE>

Don’t do this:

public class MyPage : System.Web.UI.Page {
     protected HtmlGenericControl Title;
     private void Page_Load(object sender, System.EventArgs e) { 
          Title.InnerText=GetResourceString(“PageTitle”);
      }
}

I’ve also seen examples of people creating the TITLE element as an HtmlGenericControl and adding this to the HEAD element controls collection. I’ve even seen code-behind files writing HTML code directly to the Response stream making the HTML code appear before the root HTML element.

The intent of code-behind files is to separate content from code. Exploiting the ASP.NET programming model to pull the content into the code-behind class is like using a time machine to get back to the ASP “classic” mix of HTML code and VB Script code. It’s already difficult to write maintainable code. There is no need to search for ways to make it harder.

Comments