An easy fix for the Xhtml compliance <span> problem with AspNet Controls

As I posted earlier, many AspNet controls makes it impossible to generate valid XHTML if normally used.  I had been resolving this in a non-elegant way in the past. Today, this method broke down in an odd way but it lead me to realize that there is a very simple way to fix this, override the TagKey property.

 

For example, asp:Panel renders with a <span> which prevents a lot of items from being placed on it if the page is be to Xhtml Compliant.

 

Well the solution is simple by creating a new version with just one little change as shown in the code below

namespace Lassesen.Web.UI.WebControls
{
    using System;
    using System.Web.UI;

    [ToolboxData("<{0}:Panel runat=\"server\" />")]
    public class Panel : System.Web.UI.WebControls.Panel
    {
        /// <summary>
        /// Enhanced(Corrected) Panel that renders in a Div and not a Span
        /// </summary>

        public Panel() { }
        /// <summary>
        /// Gets the <see cref="T:System.Web.UI.HtmlTextWriterTag"/> value that corresponds to this Web server control.
        /// We change the outer html tag from Span to Div for Xhtml Compliance
        /// </summary>
        /// <value></value>
        /// <returns>
        /// One of the <see cref="T:System.Web.UI.HtmlTextWriterTag"/> enumeration values.
        /// </returns>
        protected override HtmlTextWriterTag TagKey
        {
            get
            {
                return HtmlTextWriterTag.Div;
            }
        }
    }
}

 

This same trick may be done with other controls. Just add this to web config and you are in business.

 

<add tagPrefix="xhtml" namespace="Lassesen.Web.UI.WebControls" assembly="Lassesen.Web" />

 

As I said, this is a nice elegant solution (IMHO).

Comments

Popular posts from this blog

Simple WP7 Mango App for Background Tasks, Toast, and Tiles: Code Explanation

Yet once more into the breech (of altered programming logic)

Error : /ScriptResource.axd : Invalid viewstate.