Thursday, August 26, 2010

Move viewstate to bottom of the page

                                     Recently i have got a problem with in my application..That  is index page having 44,0000(nearly 9 pages ) characters length of viewstate .Hmmm.....I would like to move all the .net stuff __VIEWSTATE to the bottom of the page.

      

                                        The reason is That  page would be much more search engine friendly and it would render faster in the browser.So i have implemented fuctionality to render the viewstate on bottom of the page .I have overrided the "RenderControl" event in master page.here is the code


/// 
/// Code for moving the Viewstate to bottom of the page
///

///
public override void RenderControl(HtmlTextWriter writer)
{
using (System.IO.StringWriter stringWriter = new System.IO.StringWriter())
{
using (HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter))
{
base.Render(htmlWriter);
string html = stringWriter.ToString();
int beginPoint = html.IndexOf("<input type=\"hidden\" name=\"__VIEWSTATE\"")
{
int endPoint = html.IndexOf("/&gt;", beginPoint) + 2;
string viewstateInput = html.Substring(beginPoint, endPoint - beginPoint);
html = html.Remove(beginPoint, endPoint - beginPoint);
int formEndStart = html.IndexOf("") - 1;
if (formEndStart &gt;= 0)
{
html = html.Insert(formEndStart, viewstateInput);
}
}

writer.Write(html);
}
}

}


Copy this code and paste into master page .run the application .Now you can see _viewstate renders in bottom of the page .

1 comment:

paul said...

Is there any way to compress the view state ?