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"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-GB">
  <head>
    <meta http-equiv="Content-Type"
      content="application/xhtml+xml; charset=utf-8"/>
    <title>Default ASP.NET Form</title>
  </head>
  <body>
    <h1>Default ASP.NET Form</h1>
    <form runat="server">
      <fieldset>
        <legend>Sample form</legend>
        <input type="submit"/>
      </fieldset>
    </form>
  </body>
</html>

 

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"
    id="_ctl0">
    <input type="hidden" name="__VIEWSTATE"
      value="**random characters**" />
    <fieldset>
      <legend>Sample form</legend>
      <input type="submit"/>
    </fieldset>
  </form>
...

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...

Comments

Contribute

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.

“The most exciting phrase to hear in science, the one that heralds new discoveries, is not 'Eureka!' but 'That's funny...'” - Isaac Asimov