Google

Thursday, August 30, 2007

ASP.Net : Moving Viewstate

Search engines use spidering/crawling as a means of providing up to date data on the web, and did you know that these crawlers will ignore your page if it encounters huge chunk of viewstate on your asp.net pages? A workaround on this is to move your viewstate at the bottom of the page by overriding the render method of your form. See code below taken from “ASP.NET hacks and tips” book.

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("< type="\" name="\">);

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("") - 1;

if (FormEndStart >= 0)

{

html = html.Insert(FormEndStart, viewstateInput);

}

}

writer.Write(html);

}

1 comment:

Jon Limjap said...

Great tip, dude. :) I've been meaning to ask Eduardo Lorenzo about this (because he's doing the SEO on ASP.NET topic on the PHINUG Tech Sharing on Thursday) but now that you've put it out, I have something to refer to :)

Nga pala, if you're wondering who I am, it's LaTtEX from the MS Forums :)