ASP.NET 2.0 WebForms and SEO


This is an old story. About bad for search engines viewstate.

But many people still run their websites using webforms. First of all, because a lot of money were spent webforms development and no one wants to upgrade it to MVC.

If you view the source of your page and see something like:

1
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUENTM4MWQYBgWQAWN0bDAwJGN0bDAwJGN0bDAwJGN0bDAwJGJhc2VfY29udGVudCR3ZWJfYmFzZV9jb250ZW50JGZvb3Rlcl9hcmVhJHRtX2N1c3RvbV91c2VyY29udHJvbHNfbmF2aWdhdGlvbl9uYW1lY2hlYXBmb290ZXJfYXNjeDEkTmF2aWdhdGlvbkxpbmtzQ29udGVudA8UKwABBQ9HZW5lcmljX0NvbnRlbnRkBUVjdGwwMCRjdGwwMCRjdGwwMCRjdGwwMCRiYXNlX2NvbnRlbnQkd2ViX2Jhc2VfY29udGVudCRHZW5lcmljQ29udGVudDEPFCsAAWRkBUhjdGwwMCRjdGwwMCRjdGwwMCRjdGwwMCRiYXNlX2NvbnRlbnQkd2ViX2Jhc2VfY29udGVudCRzaXRlTWVzc2FnZUNvbnRlbnQPFCsAAWRkBWFjdGwwMCRjdG

You need to think about moving viewstate to the bottom of your page. First of all because search engines like to index only first X kbytes.

And also content on top of the document is ranked higher.

To do this, you should override Render method of base class of your page.

For example,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/// <summary>
/// That is new default page  class
/// </summary>
public abstract class MyPage : System.Web.UI.Page
{
    public MyPage()
    {
 
    }
 
 
    /// <summary>
    /// Moves viewstate to bottom
    /// </summary>
    /// <param name="writer"></param>
    protected override void Render(HtmlTextWriter writer)
    {
        System.IO.StringWriter stringWriter = new System.IO.StringWriter();
        HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
        base.Render(htmlWriter);
        string html = stringWriter.ToString();
        int StartPoint = html.IndexOf("<input type=\"hidden\" name=\"__VIEWSTATE\"");
        if (StartPoint >= 0)
        {
            int EndPoint = html.IndexOf("/>", StartPoint) + 2;
            string viewstateInput = html.Substring(StartPoint, EndPoint - StartPoint);
            html = html.Remove(StartPoint, EndPoint - StartPoint);
            int FormEndStart = html.IndexOf("</form>") - 1;
            if (FormEndStart >= 0)
            {
                html = html.Insert(FormEndStart, viewstateInput);
            }
        }
        writer.Write(html);
    }
}

To use it. You should change parent class of your page class

1
2
3
public partial class _Default : System.Web.UI.Page
// change to 
public partial class _Default : MyPage

Usually you can find this in your code behind file. In this example, default.aspx.cs.

Performance penalty is minimal cause RegEx is quite fast. If you want to make things really fast – try to remove form runat=’server’ from your page and avoid server-controls on public pages.

Tags: ,