Description
The purpose of this article is demonstrate how to move the ViewState content to the bottom of your WebForm in an aspx page.
There are many benefits of moving your page's ViewState to the bottom of your WebForm.The most desirable reasons include: it can increase your page rank with search engines because many search algorithms determine page relevancy by searching for keywords at the beginning of the document; in cases where your viewstate is large, the perceived loading time for the client will appear to be faster since your page's content is loading before the ViewState.
Code
STEP 1: Create a class called "ViewStateModule" and inherit the IHttpModule interface. Below is the contents of the class.
void IHttpModule.Init(HttpApplication pHttpApp)
{
pHttpApp.BeginRequest += new EventHandler(OnBeginRequest);
}
void IHttpModule.Dispose() { }
internal void OnBeginRequest(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
if (app != null)
{
if (app.Request.Url.OriginalString.Contains(".aspx"))
{
app.Response.Filter = new Filter(
app.Response.Filter
);
}
}
}
STEP 2: Include a nested private class inside "ViewStateModule" called "Filter" that inherits from System.IO.MemoryStream. Below is the class contents.
private Stream _objStream;
internal Filter(Stream pStream)
{
this._objStream = pStream;
}
public override void Write(
byte[] buffer, int offset, int count
)
{
string str = Encoding.Default.GetString(buffer);
int iStartIndex = str.IndexOf(
"<input type=\"hidden\" name=\"__VIEWSTATE\""
);
if (iStartIndex != -1)
{
int iEndIndex = str.IndexOf("/>", iStartIndex) + 2;
string strViewState = str.Substring(
iStartIndex, iEndIndex - iStartIndex
);
str = str.Remove(iStartIndex, iEndIndex - iStartIndex);
int iInsertIndex = str.IndexOf("</form>");
if (iInsertIndex != -1)
{
str = str.Insert(iInsertIndex, strViewState);
}
}
byte[] arryOut = Encoding.Default.GetBytes(str);
this._objStream.Write(
arryOut, 0, arryOut.GetLength(0)
);
}
STEP 3: Add the HttpModule by placing the XML seen below into your Web.config file. You should place it within the system.web node.
<httpModules>
<add type="ViewStateModule" name="ViewStateModule" />
</httpModules>

1 comments:
I've seen lots of blogs and examples on this topic. This is the first time I've seen it done inheriting MemoryStream. Now I can see why. Cool post.
Post a Comment