Cleaning up ASP.NET head tag with Control Adapters

ASP.NET offers a lot of functionality but has always suffered from being SEO unfriendly. It injects a lot of javascript for postback, tables rather than div for server controls like GridView and inline meta tags in the head section of the HTML which makes it difficult to read. The title tag is the one most important part of search engine optimisation and when you look at an page you will find that the title tag is spread on 3 lines in the html source code as follows:

<head id="Head"><title>
	Test Page
</title><meta name="keywords" content="test keywords" />...

If you have meta description tag, css, favicon or any other elements in the head section, they will be rendered inline. The title has white spaces around it. So how do you solve this problem? The answer lies in control adapters. You basically override the default rendering of the controls as follows:

<pre>using System.Web.UI;
using System.Web.UI.Adapters;

namespace Gis.CMS.Presentation
 public class HtmlTitleAdapter : ControlAdapter
 protected override void Render(HtmlTextWriter writer)

And you will need a .browser file in your App_Browsers folder in your .net application as follows:

 <browser refID="Default">
 <adapter controlType="System.Web.UI.HtmlControls.HtmlTitle"
 adapterType="Gis.CMS.Presentation.HtmlTitleAdapter" />

The above code is only to fix the title so that it displays properly:

<pre><title>Test Page</title>

I haven't included code to fix meta tags like keywords and description and link for css and favicon though to keep things simple.

If you use the Page.MetaKeywords property available in .net 4, you will find that your keywords are not displayed when using the control adapter. You will have to do one of the following to fix it:
Insert a blank keywords meta tag in your html and then override it in your code behind or programmatically add the meta keywords elements using HtmlMeta control.

comments powered by Disqus