Thursday, 23 September 2010

asp:Menu controls not working in Chrome/Safari

I faced a small issue today with asp:Menu controls not working properly in Chrome or Safari the first time the page is loaded. However, if I refresh the page, the contents seem to load fine.
The underlying problem is the way Chrome manages it's adaptors and we need to be able to clear these out and refresh the page if this situation occurs.

I have therefore written an OnInit event for any ASP.NET page or user control in which the menu is placed. Simply just add it in the code behind...


Fix Menu rendering in Chrome and Safari
protected override void OnInit(EventArgs e)
{
    // For Chrome and Safari
    if (Request.UserAgent.IndexOf("AppleWebKit") > 0)
    {
        if (Request.Browser.Adapters.Count > 0)
        {
            Request.Browser.Adapters.Clear();
            Response.Redirect(Page.Request.Url.AbsoluteUri);
        }
    }
}



- Using the "AppleWebKit" we can identify these browsers
- By checking more than one adapter exists, we avoid re-directing every time; this only needs to be done on the first hit.
- We Re-Direct back to itself the first time the page is hit.

No comments: