IE8 beta 1 browser version targeting and ASP.NET Themes

You might find that when you add the meta tag required to force IE8 beta 1 into IE7 (or 6) rendering mode into your ASP.NET page (or Master Page) that it doesn’t work as expected…. IE8 continues to render the site in full standards mode. The reason might be that in beta 1 of IE8 the “X-UA-Compatible” meta tag must be the first element in the page head element and by default ASP.NET will insert the link tags to the CSS files in your theme at the beginning of the head element of your page (or Master Page), before any other elements that might actually be defined in the .aspx or .master file.

To fix this, add the following code to the page’s (or Master Page’s) PreRender event handler (Page_PreRender):

// Move browser tageting meta tag to top of header
HtmlMeta meta = null;
int metaXUACompatIndex = -1;
foreach (Control ctl in page.Header.Controls)
{
    meta = ctl as HtmlMeta;
    if (meta == null)
        continue;

    if (meta.HttpEquiv == "X-UA-Compatible")
    {
        // Grab index
        metaXUACompatIndex = page.Header.Controls.IndexOf(meta);
        break;
    }
}
if (metaXUACompatIndex > 0)
{
    HtmlMeta metaXUACompat = page.Header.Controls[metaXUACompatIndex] as HtmlMeta;
    page.Header.Controls.RemoveAt(metaXUACompatIndex);
    page.Header.Controls.AddAt(0, metaXUACompat);
}

This will move the browser targeting meta tag to the top of the list so that IE8 will honour it.

Advertisements