Wednesday, April 8, 2009
As we know that state of all ASP.NET controls is maintained __VIEWSTATE hidden field in encrypted format.
By default this _VIEWSTATE HTML hidden field will be rendered at the top inside body tag (just below form tag). If we have lot of control data to be stored in ViewState then length of the viewstate will be more hence page will take time to load and also reduces rank in search engine as all the junk will be loaded at the top of actual content.
So to make web page more search engine friendly and to make page render faster we may wish to move this __VIEWSTATE to the bottom of the page.
In this manner we can make our web page more search engine friendly by moving ViewState to the bottom of the page and not to gunk up search engines as the real content will be at the top of the HTMl page.
To achieve this in ASP.NET 2.0 we need to tweek the way the page is render by overriding the page Rrender() method and move the _VIEWSTATE from its default location at the top of the page to the bottom of the page. This results in better search engine spidering.
protected override void Render(System.Web.UI.HtmlTextWriter writer)
System.IO.StringWriter stringWriter = new System.IO.StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
string html = stringWriter.ToString();
int StartPoint = html.IndexOf("<input type=\"hidden\" name=\"__VIEWSTATE\"");
if (StartPoint >= 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("</form>") - 1;
if (FormEndStart >= 0)
html = html.Insert(FormEndStart, ViewStateInput);
Instead of overriding Render() of all pages its better to do this in the Base class or in the master page.
However there is a problem when user clicks on a button before the page is loaded then ViewState will not be available to the server. It will not be able to process the ViewState.
In ASP.NET 3.5 SP1
In order to render __EVENTTARGET, __EVENTVALIDATION, __EVENTARGUMENT etc at the bottom of the page we need to set renderAllHiddenFieldsAtTopOfForm to false in web.config which true is by default.
<pages renderAllHiddenFieldsAtTopOfForm="false" />
Note: This will not move __VIEWSTATE to the bottom of the page.
Also Read other Top Articles
- JSON Serialization in VS 2008
- Implementing Forms Authentication in Silverlight Application.
- Making GridView Rows or Individual Cells Clickable and Selectable.
- Enabling browser back button for GridView Paging and Sorting in Ajax 1.1 and 3.5 (using Visual Studio 2005/ Visual studio 2008)
- How to pass values from User Control to Page or calling Page methods from User Control.
- What is WCF?
- New features in C# 4.0
- C# to VB.NET and VB.NET to C# online free converter tools.