Valid XHTML within .NET

The Problem

In their original out-of-the-box format Microsoft's ASP.NET HtmlControls and WebControls do not produce XHTML compliant code. Microsoft has thoughtfully (and thankfully) allowed developers to extend the controls to add user-defined custom functionality. It will be through this added functionality that we will be able to output valid code.

To start with, let us look at the code that the current default implementation produces. Create a new ASP.NET page in the root folder of your IIS development machine; call the page currentform.aspx and copy the code in Listing 01 (you'll notice were using the "XHTML 1.0 Strict" DTD in this example):

Listing 01

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
<html xmlns="" xml:lang="en-GB">
    <meta http-equiv="Content-Type"
      content="application/xhtml+xml; charset=utf-8"/>
    <title>Default ASP.NET Form</title>
    <h1>Default ASP.NET Form</h1>
    <form runat="server">
        <legend>Sample form</legend>
        <input type="submit"/>


Point your browser at currentform.aspx , you should see something similar to Figure 1a .

Figure 1d
Figure 1a

If you view the source code you should see the following HTML (formatted here for brevity):

  <form name="_ctl0" method="post" action="currentform.aspx"
    <input type="hidden" name="__VIEWSTATE"
      value="**random characters**" />
      <legend>Sample form</legend>
      <input type="submit"/>

As you can see ASP.NET has added the name , method , action and id attributes as well as a hidden field called __VIEWSTATE containing the forms encrypted triplet view-state values. If we try and validate this document by uploading a copy of the source-code to the W3C's validating service you'll see we get the following response:

This page is not Valid XHTML 1.0 Strict!

The validating service goes on to tell us we have two errors:

  1. There is no attribute called name within a form tag.
  2. The document type does not allow element input here because input is an inline tag when a block-level tag was expected.

The remainder of this document will focus on fixing these two errors.

You might also like...



Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Some people, when confronted with a problem, think "I know, I’ll use regular expressions." Now they have two problems.” - Jamie Zawinski