July 28 2008

Moving the ViewState Hidden Input Control

A page with a heavy ViewState takes longer to load.  A user with a slow conenction (dial-up or GPRS) will be waiting longer for the page to be served.

Additionally, many search engines have a page cut-off length.  I believe Google pretty much stops indexing a page after 100k.  Not that you should have a page that large, but if you have a large page and a large viewstate, google may well be ignoring your content because of your bloated viewstate.

This article from Web Master World, talks of a solution to move the ViewState Input control to the end of the page Form.  It’s in VB.Net, so I converted it to C# here:

// This method overrides the Render() method 
// for the page and moves the ViewState
// from its default location at the top of the page 
// to 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("= 0) { //does __VIEWSTATE exist? 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); }

One last caveat is that I have zero idea if this helps with search engine indexing, but it will certainly help to make a page appear to load faster for slow connecting users. This is not a solution to the problem of a large view state, but rather a treatment for a symptom.

Comments (View)
blog comments powered by Disqus

Please...

Leave a comment if this has helped or offended you.

StackOverflow Id