Solution of Validation of viewstate MAC failed

Validation of viewstate MAC failed / The state information is invalid for this page and might be corrupted

so, all you need on an *.aspx page for generating this error:

Any DataSource Control (SqlDataSource, XmlDataSource…)
GridView bound / unbound to DataSource
Using DataKeyNames in GridView
Using elements
Something on the *.aspx page which takes a while till rendered (as for example banners, external pictures etc.)
Button

One solution to this problem

Create a small class called BasePage that fixes the issues, so you just have to extend your page from BasePage instead of Page:

public class BasePage : Page
{
private static string[] aspNetFormElements = new string[]
{
“__EVENTTARGET”,
“__EVENTARGUMENT”,
“__VIEWSTATE”,
“__EVENTVALIDATION”,
“__VIEWSTATEENCRYPTED”,
};

protected override void Render(HtmlTextWriter writer)
{
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
base.Render(htmlWriter);
string html = stringWriter.ToString();
int formStart = html.IndexOf(“= 0)
endForm = html.IndexOf(“>”, formStart);

if (endForm >= 0)
{
StringBuilder viewStateBuilder = new StringBuilder();
foreach (string element in aspNetFormElements)
{
int startPoint = html.IndexOf(“= 0 && startPoint > endForm)
{
int endPoint = html.IndexOf(“/>”, startPoint);
if (endPoint >= 0)
{
endPoint += 2;
string viewStateInput = html.Substring(startPoint, endPoint – startPoint);
html = html.Remove(startPoint, endPoint – startPoint);
viewStateBuilder.Append(viewStateInput).Append(“\r\n”);
}
}
}

if (viewStateBuilder.Length > 0)
{
viewStateBuilder.Insert(0, “\r\n”);
html = html.Insert(endForm + 1, viewStateBuilder.ToString());
}
}

writer.Write(html);
}
}

for more details refer http://blogs.msdn.com/tom/archive/2008/03/14/validation-of-viewstate-mac-failed-error.aspx

Advertisements

~ by UTS on May 17, 2009.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: