ASP.NET Viewstate to bottom of page.

Something that bugs me from time to time is the base64 encoded viewstate in the source code. It might be worth your while moving it to the bottom of the page.

There are mixed opinions online in regards to whether or not having your viewstate at the top of the page has an effect on Google/Bing rankings.

It is a hidden element so spiders should ignore it, but do they? Let’s be safe rather than sorry.

Drop this code into your code behind file. I put this into my master page so all child pages have their viewstate injected into the bottom of the page.

protected override void Render(System.Web.UI.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);
    }

It works quite nicely. =D

Resource: hanselman.com

Advertisements

Published by

Alan Feekery

Developer, Gamer, Musician, Cyclist and big Motorsport fan... enjoys the odd cup of coffee :)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s