Freigeben über


Validation of viewstate MAC failed error

-- 3/17/2009 UPDATE --

If you are using .NET 2.0 or later, please upgrade to .NET 3.5 SP1 (.NET 2.0 SP2) as it has a fix in it that should resolve this issue.  If you update and still have the problem, please post here so we know.

-- 3/17/2009 UPDATE --

 

Issue Description

You can get this Exception:

 

 HttpException (0x80004005): Validation of viewstate 
MAC failed. If this application is hosted by a Web 
Farm or cluster, ensure that  configuration 
specifies the same validationKey and validation 
algorithm. AutoGenerate cannot be used in a cluster.

 

when the following preconditions are true:

1. You aren't using a web farm.

2. It appears when using built-in databound controls such as GridView, DetailsView or FormView which utilize “DataKeyNames”.

3. It appears if you have a large page which loads slowly for any reason.

If following preconditions are true and you click a postbacking control/link and the page hasn't loaded completely in client browser, you might get the "Validation of ViewState MAC failed" exception.

When this happens, if you just try setting the page property "EnableViewStateMac" to false, it does not solve the problem, it just changes the error message in same navigation behavior:

 

 The state information is invalid for 
this page and might be corrupted.

 

Other exceptions that seem to be the same problem look like:

 Exception: System.Web.HttpUnhandledException
Message: Exception of type 'System.Web.HttpUnhandledException' was thrown.
Source: System.Web
at System.Web.UI.Page.HandleError(Exception e)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, 
Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, 
Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest()
at System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context)
at System.Web.UI.Page.ProcessRequest(HttpContext context)
at ASP.test_aspx.ProcessRequest(HttpContext context)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExec
utionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& 
completedSynchronously) 

Nested Exception 

Exception: System.ArgumentException
Message: Invalid postback or callback argument. 
Event validation is enabled using in configuration 
or <%@ Page 
EnableEventValidation="true" %> in a page. For security purposes, this feature 
verifies that arguments to postback or callback 
events originate from the server control that 
originally rendered them. If the data is valid 
and expected, use the 
ClientScriptManager.RegisterForEventValidation 
method in order to register the postback or 
callback data for validation.
Source: System.Web
at System.Web.UI.ClientScriptManager.ValidateEvent(String uniqueId, String 
argument)
at System.Web.UI.Control.ValidateEvent(String uniqueID, String eventArgument)
at System.Web.UI.WebControls.TextBox.LoadPostData(String postDataKey, 
NameValueCollection postCollection)
at System.Web.UI.WebControls.TextBox.System.Web.UI.IPostBackDataHandler.LoadPostData(St
ring postDataKey, NameValueCollection postCollection)
at System.Web.UI.Page.ProcessPostData(NameValueCollection postData, Boolean 
fBeforeLoad)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, 
Boolean includeStagesAfterAsyncPoint) 

and

 Content-Length:1232
Content-Type:application/x-www-form-urlencoded
Accept:*/*
Accept-Encoding:gzip,deflate
Accept-Language:en-us
Cookie:ASP.NET_SessionId=skk4vriy1lzghm55bicesz45; 
Host:
User-Agent:T-Mobile Dash Mozilla/4.0 (compatible; MSIE 4.01; Windows CE; 
Smartphone; 320x240) UA-OS:Windows CE (Smartphone) - Version 5.1
UA-color:color16
UA-pixels:320x240
x-wap-profile:""
UA-Voice:TRUE
UA-CPU:x86
X-Forwarded-For: 

Thread: 964
Date: 2007-10-25 13:47:03,925
NDC: (null) 

Exception: System.Web.HttpException
Message: Validation of viewstate MAC failed.
 If this application is hosted by a Web 
Farm or cluster, ensure that  configuration 
specifies the same validationKey and validation
algorithm. AutoGenerate cannot be used in a cluster.
Source: System.Web
at System.Web.UI.ViewStateException.ThrowError(Exception inner, String 
persistedState, String errorPageMessage, Boolean macValidationError)
at System.Web.UI.ObjectStateFormatter.Deserialize(String inputString)
at 
System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter.Deserialize(String 
serializedState)
at System.Web.UI.Util.DeserializeWithAssert(IStateFormatter formatter, String 
serializedState)
at System.Web.UI.HiddenFieldPageStatePersister.Load()
at System.Web.UI.Page.LoadPageStateFromPersistenceMedium()
at System.Web.UI.Page.LoadAllState()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, 
Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, 
Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest()
at System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context)
at System.Web.UI.Page.ProcessRequest(HttpContext context)
at ASP.test_aspx.ProcessRequest(HttpContext context) 
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExec
utionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& 
completedSynchronously) 

Nested Exception 

Exception: System.Web.UI.ViewStateException
Message: Invalid viewstate. 
Client IP: 
Port: 61362
User-Agent: T-Mobile Dash Mozilla/4.0 (compatible; MSIE 4.01; 
Windows CE; Smartphone; 320x240)
ViewState: 
/wEPDwUJMjUyNTI1NDMyD2QWAmYPZBYCAgEPZBYEAlAPD2QWAh4Kb25rZXlwcmVzcwUqcmV0dXJuIGNsaWNr
QnV0dG9uKGV2ZW50LCdjdGwwMF9pYlNlYXJjaCcpZAJWD2QWBAIBD2QWBAIDDw9kFgIfAAUxcmV0dXJuIGNs
aWNrQnV0dG9uKGV2ZW50LCdjdGwwMF9jcDFfRmxhc2hCdXR0b24nKWQCBg8UKwACDxYCHghJbWFnZVVybAUj
fi9faG9tZV9hZF91bml0cy9ob21lX2FkdW5pdHMxMS5qcGdkDxQrAAMWCB4LQ29vcmRpbmF0ZXMFFzAsMCwy
NTUsMCwyMjQsMTEwLDAsMTEwHgtOYXZpZ2F0ZVVybAUGfi9uZmwvHg1BbHRlcm5hdGVUZXh0BSNUaGUgcnVz
aCB0byBGYXRoZWFkIGZvb3RiYWxsIGlzIG9uIR4GVGFyZ2V0ZRYIHwIFGzQ5OCwwLDQ1OCwxMTAsMjI0LDEx
MCwyNTUsMB8DBRB+L2hlcm9lcy9iYXRtYW4vHwQFOVRoZSBEYXJrIEtuaWdodCBpcyBoZXJlLi4uYW5kIGhl
J3MgYnJvdWdodCBzb21lIGZyaWVuZCdzIR8FZRYIHwIFGzcwOCwxMTAsNzM5LDAsNDk4LDAsNDU4LDExMB8D
BQZ+L21sYi8fBAUhTUxCIGhpdHMgYSBob21lIHJ1biB3aXRoIEZhdGhlYWQhHwVlFCsBAwICAgICAmQCAw8P
FgIeB1Zpc2libGVoZBYCAgEPZBYCZg8PZBYCHwAFMnJldHVybiBjbGlja0J1dHRvbihldmVudCwnY3RsMDBf
Y3AxX1N0YXRpY0J1dHRvbicpZBgBBR5f... 

Nested Exception 

Exception: System.Web.HttpException
Message: Unable to validate data.
Source: System.Web
at System.Web.Configuration.MachineKeySection.GetDecodedData(Byte[] buf, Byte[] 
modifier, Int32 start, Int32 length, Int32& dataLength)
at System.Web.UI.ObjectStateFormatter.Deserialize(String inputString) 

 

Root Cause

This exception appears because Controls using DataKeyNames require Viewstate to be encrypted. When Viewstate is encrypted (Default mode, Auto, is to encrypt if controls require that, otherwise not), Page adds <input type="hidden" name="__VIEWSTATEENCRYPTED" id="__VIEWSTATEENCRYPTED" value="" /> field just before closing of the <form> tag. But this hidden field might not have been rendered to the browser with long-running pages, and if you make a postback before it does, the browser initiates postback without this field (in form post collection). End result is that if this field is omitted on postback, the page doesn't know that Viewstate is encrypted and causes the aforementioned Exception. I.E. page expects to be fully-loaded before you make a postback.

And by the way similar problem is with event validation since __EVENTVALIDATION field is also rendered on the end of the form. This is a security feature that ensures that postback actions only come from events allowed and created by the server to help prevent spoofed postbacks. This feature is implemented by having controls register valid events when they render (as in, during their actual Render() methods). The end result is that at the bottom of your rendered <form> tag, you'll see something like this: <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="AEBnx7v.........tS" />. When a postback occurs, ASP.NET uses the values stored in this hidden field to ensure that the button you clicked invokes a valid event. If it's not valid, you get the exception above.

The problem happens specifically when you postback before the EventValidation field has been rendered. If EventValidation is enabled (which it is, by default), but ASP.net doesn't see the hidden field when you postback, you also get the exception. If you submit a form before it has been entirely rendered, then chances are the EventValidation field has not yet been rendered, and thus ASP.NET cannot validate your click.

Workarounds

1. Set enableEventValidation to false and viewStateEncryptionMode to Never as follows:

 <pages enableeventvalidation="false" 
    viewstateencryptionmode="Never">

This has the unwanted side-effect of disabling validation and encryption.  On some sites, this may be ok to do, but it isn't a best practice, especially in publicly facing sites.

 

2. Another way around the problem is to mark the form as disabled and then enable it in script once the load is complete:

   function enableForm() { 
      document.getElementById("form").disabled = false; 
  } 

  window.onLoad = enableForm();

 

Or you can disable the individual form elements and enable them once everything is loaded:

   function disableElements(elements) { 
  for (var i = elements.length - 1; i >= 0; i--) { 
    var elmt = elements[i]; 

    if (!elmt.disabled) { 
      elmt.disabled = true; 
    } 
    else { 
      elmt._wasDisabled = true; 
    } 
  } 
} 

function disableFormElements() { 
  disableElements(_form.getElementsByTagName("INPUT")); 
  disableElements(_form.getElementsByTagName("SELECT")); 
  disableElements(_form.getElementsByTagName("TEXTAREA")); 
  disableElements(_form.getElementsByTagName("BUTTON")); 
  disableElements(_form.getElementsByTagName("A")); 
} 

function enableElements(elements) { 
  for (var i = elements.length - 1; i >= 0; i--) { 
    var elmt = elements[i]; 
    if (!elmt._wasDisabled) { 
      elmt.disabled = false; 
    } 
    else { 
      elmt._wasDisabled = null; 
    } 
  } 
} 

function enableFormElements() { 
  enableElements(_form.getElementsByTagName("INPUT"));
  enableElements(_form.getElementsByTagName("SELECT"));
  enableElements(_form.getElementsByTagName("TEXTAREA"));
  enableElements(_form.getElementsByTagName("BUTTON"));
  enableElements(_form.getElementsByTagName("A"));
} 

Make sure that the variable _form is set to the ASP.net form on the page. Then just call enableFormElements() and disableFormElements().

 

3. The last way to workaround this problem is to override the Render Event of the page to place the hidden fields for Encrypted Viewstate and Event validation on the top of the form.  This will ensure that these things get written out before anything that can submit the form:

 

 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();
  string[] aspnet_formelems = new string[5];
  aspnet_formelems[0] = "__EVENTTARGET";
  aspnet_formelems[1] = "__EVENTARGUMENT";
  aspnet_formelems[2] = "__VIEWSTATE";
  aspnet_formelems[3] = "__EVENTVALIDATION";
  aspnet_formelems[4] = "__VIEWSTATEENCRYPTED";
  foreach (string elem in aspnet_formelems)
  {
    //Response.Write("input type=""hidden"" name=""" & abc.ToString & """")
    int StartPoint = html.IndexOf("<input type=\"hidden\" name=\"" + 
      elem.ToString() + "\"");
    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 FormStart = html.IndexOf("<form");
      int EndForm = html.IndexOf(">", FormStart) + 1;
      if (EndForm >= 0)
        html = html.Insert(EndForm, ViewStateInput);
    }
  }

  writer.Write(html);
}
Update

Another solution based on #3 above, special thanks to Alex for posting this in the comments below.  He wrote 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("<form");
     int endForm = -1;
     if (formStart >= 0)
       endForm = html.IndexOf(">", formStart);
  
     if (endForm >= 0)
     {
       StringBuilder viewStateBuilder = new StringBuilder();
       foreach (string element in aspNetFormElements)
       {
         int startPoint = html.IndexOf("<input type=\"hidden\" name=\"" + element + "\"");
         if (startPoint >= 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);
   }
 }

There are many other workarounds for the above mentioned problem; however no definite solution.

Further Information around this problem

ASP.NET Forum link

Connect Bug

Also, if you use Server.Transfer on your page, you you can also run into this issue.  For information on that, take a look at the documentation found here.  Specifically:

If you set preserveForm to true and if the enableViewStateMac attribute of the pages configuration element is true, ASP.NET will raise an exception when Transfer is executed because the view state from the page that calls Transfer is not valid on the destination page. One of the preserved form fields on the calling page is the hidden __VIEWSTATE form field, which holds the view state for the page. When enableViewStateMac is true, ASP.NET runs a message authentication check on the view state of the destination page when the page is posted back from the client and the check will fail.

And there is a KB article on this with a few resolutions.

kick it on DotNetKicks.com

Comments

  • Anonymous
    March 14, 2008
    You've been kicked (a good thing) - Trackback from DotNetKicks.com

  • Anonymous
    March 14, 2008
    We are having this problem sometimes in subtext when the page is downloaded from slow connections. I'll have a look if I can apply these suggestions to my problem. Than you for sharing Simo

  • Anonymous
    March 14, 2008
    Thank you for the solutions. I particularly like the third and will use that from now on.

  • Anonymous
    March 15, 2008
    We used to run into this problem when using large wizard controls. Viewstate would get very bloated and users with slow connections would sometimes click on the "next" button before viewstate was loaded. Our "solution" is to compress viewstate. This really seems to have done the trick: http://www.codeproject.com/KB/viewstate/ViewStateCompression.aspx

  • Anonymous
    March 15, 2008
    Only thing that helped me is to add machine key in web.config. And I tried almost everything else... You can google for generation tool (http://aspnetresources.com/tools/keycreator.aspx)

  • Anonymous
    March 15, 2008
    That is a very good suggestion Rob, compressing the Viewstate can certainly help in some situations and helps to keep the pages download faster which always helps allowing the entire page to load.

  • Anonymous
    March 15, 2008
    Hudo, that is usually what we have to do if we are using a Webfarm since you want all the processes to use the same MachineKey. Take a look at http://support.microsoft.com/kb/312906 for another way, which allows you to create your own tool to create a MachineKey.

  • Anonymous
    March 16, 2008
    ASP.NET - Validation of viewstate MAC failed!

  • Anonymous
    March 16, 2008
    I posted about this some time ago. My previous post: Potential solution for &quot;Validation of viewstate

  • Anonymous
    March 16, 2008
    Last week I was working with on a case where they were getting this error message HttpException (0x80004005):

  • Anonymous
    March 18, 2008
    The comment has been removed

  • Anonymous
    March 18, 2008
    The firewall is a very good catch also.  We haven't seen as many of those but it certainly can cause the same problem.  Either increasing the amount of data that it allows through, or trimming the viewstate are the only ways around that.

  • Anonymous
    March 22, 2008
    Tess&#39;s If broken it is, fix it you should blog is always good for a read. Tess is an escalation engineer

  • Anonymous
    April 01, 2008
    I've just tried to implement your override Render method and run into a couple of small problems. I don't really understand this: int FormStart = html.IndexOf(">form"); int EndForm = html.IndexOf("<", FormStart) + 1; Surely FormStart will never be true, unless you mean to match "<form" rather than ">form"? Also EndForm would match inside the next tag (in my case a div), so you'd end up with "<<input type.../>div>" I changed the IndexOfs to match "<form" and ">" respectively and it seems to work, with the hidden input fields being inserted following the <form> tag. Also, in the array of aspnet_formelems, you don't have the VIEWSTATEENCRYPTED tag. I thought the whole point of the workaround was to put this at the top just after the form tag. So I also added this to your array and the issue seems to be resolved. Is this what you meant originally, or have I misinterpreted your solution? Thanks, Simon

  • Anonymous
    April 01, 2008
    bastett, You are right, thanks for finding that.  That is what I get for trying to do the HTML of a < and >.  And good catch on the VIEWSTATEENCRYPTED.  I have updated the post to correct those. Thanks

  • Anonymous
    April 02, 2008
    A common thread in this is problems with the Viewstate in a hidden field - we use Infragistics GridView controls and the size of the Viewstate field frankly becomes ridicoules as the amount of data displayed increased. Possibly this tip from MSDN's Wicked Code (see figure 4) is a general and recommendable way to work around this problem: http://msdn.microsoft.com/msdnmag/issues/06/07/WebAppFollies/default.aspx#S4 PS. That entire article is excellent and I highly recommend reading it!

  • Anonymous
    April 03, 2008
    Thanks Thomas.  That is a a good article for anyone to read and review.  Storing viewstate in session has good and bad about it, but if you can handle the additional memory on the server, it will work very well and also allows for smaller pages for your clients to download.

  • Anonymous
    April 16, 2008
    The comment has been removed

  • Anonymous
    April 16, 2008
    Yes.  That is a good thing to make sure.  There are other things that can cause this if you are using Web Gardens or a Web Farm

  • Anonymous
    May 02, 2008
    My webpage works fine on my a workstation but gives "Validation of viewstate MAC failed" error when I run it from the PDA.. Any Idea why this wouild be happening? I tried all the solutions given

  • Anonymous
    May 02, 2008
    Jai, Is it a large page?  Maybe the PDA has a limit for how much data it will download and cuts off the viewstate.

  • Anonymous
    May 02, 2008
    Page is not large. Let me explain the exact problem I have meta refresh tag on the page which refreshes the page every 20 seconds. First time when the page is loaded on the PDA it refreshes without any issues. when the user clicks on a button he is redirected to a different page. After he submits that page he is redirected to the first page with th erefresh meta tag. First page with Refresh meta tag load and when the refresh is happening it throws this error. I hpe I was able to explain the issue. Appreciate your help on this.

  • Anonymous
    May 05, 2008
    Jai, If you are on a PDA and refreshing every 20 seconds, do you need viewstate?  Could you turn that off?  If you aren't using state, that would make the page much smaller also.  Are there controls which you want to keep their state between refreshes?

  • Anonymous
    May 08, 2008
    Btw.... how can you disable a form?! or enable it?.. it tried your method but it pops a javascript error.

  • Anonymous
    May 08, 2008
    Martin, What is the error you are seeing?

  • Anonymous
    May 11, 2008
    If you're getting this error and you're sure that you are not hosting your web app on a web farm, then this blog post has most of the information you need. All that because someone decided it would be best...

  • Anonymous
    May 14, 2008
    We've been having this exact problem and its caused by having a large page which loads slowly. Your workaround number 3 worked great for us however we've noticed a small issue in the html rendered to the page. The __EVENTVALIDATION was rendered in a div at the bottom of the page, however the __EVENTVALIDATION is now rendered at the top of the page which means this div is blank. Firefox seems to handle this fine however IE doesn't, and it messes up the style of our website. I didn't write the CSS for the website so I don't want to go messing around with it as my CSS skills aren't the best, can you see any issues with me removing the last empty div tag from the html before calling writer.Write(html); in your code?

  • Anonymous
    May 15, 2008
    Chris, I don't see any problem with that.  You should be able to do that without any issues.

  • Anonymous
    May 26, 2008
    i dono abt these things ..becuase iam a tester ...

  • Anonymous
    May 27, 2008
    I have removed the view state from the page. The issues that I was facing earlier is gone. But now if the user click on teh back button a couple of times he gets this error "Validation of viewstate MAC failed error" Thsi does not happen on the workstation.

  • Anonymous
    May 28, 2008
    Shetty, I hope this page helped you then.  Let me know if you have any problems or questions.

  • Anonymous
    May 28, 2008
    Jai, The easiest way to track something like that down is if you can reproduce it and then get a network trace to see what is being passed back and forth from the server to the client and vice versa.

  • Anonymous
    June 02, 2008
    Hi All ~ If I am facing the problem after deployment; is there any way out to solve the problem without writing code? otherwise I have to test n create the package again. Please reply....

  • Anonymous
    June 02, 2008
    Raj, It depends of if you consider changes to your config files changes.  If if it just that the MAC isn't sync'ed and you are using a web farm.  Otherwise, I don't know of a way without code changes.

  • Anonymous
    July 09, 2008
    One other thing that can cause errors like this is if there is a second form tag on the page.  So make sure there is just the one form tag that is doing the asp.net post.

  • Anonymous
    July 15, 2008
    Hi, I love your post and the third solution. It really fixed my problem. Although there are several potential bugs in your code if the html is not well formed (for whatever reason). I've written a small class called BasePage that fixes those issues and improves the performance a little bit. Then the only thing to do is to extend BasePage instead of Page. Check it out:    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("<form");            int endForm = -1;            if (formStart >= 0)                endForm = html.IndexOf(">", formStart);            if (endForm >= 0)            {                StringBuilder viewStateBuilder = new StringBuilder();                foreach (string element in aspNetFormElements)                {                    int startPoint = html.IndexOf("<input type="hidden" name="" + element + """);                    if (startPoint >= 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("rn");                        }                    }                }                if (viewStateBuilder.Length > 0)                {                    viewStateBuilder.Insert(0, "rn");                    html = html.Insert(endForm + 1, viewStateBuilder.ToString());                }            }            writer.Write(html);        }    }

  • Anonymous
    July 15, 2008
    Alex, Thanks for doing that.  That is very useful.

  • Anonymous
    August 11, 2008
    The comment has been removed

  • Anonymous
    August 12, 2008
    I've introduced a purely javascript based approach that works well enough for me, and doesn't require you to setup your own string builder (which takes up some memory).            ScriptManager.RegisterOnSubmitStatement(this, typeof(Page), "form disabler", @" if(typeof(_PageReadyForSubmit) == 'undefined' || _PageReadyForSubmit!= true) {    return false; } ");            ScriptManager.RegisterStartupScript(this, typeof(Page), "form re-enabler", @" _PageReadyForSubmit= true; ", true);

  • Anonymous
    August 13, 2008
    Clifford, Thanks for the additional workaround.  That is also a clean way to do it.

  • Anonymous
    August 15, 2008
    The comment has been removed

  • Anonymous
    August 25, 2008
    Beware of option 3 if you use Response.write anywhere in your code.  Anything you render using response.write will appear before the very top of your html, regardless of whether it's called from a .aspx file or from your codebehind.  Using the shortcut <%= %> fixes .aspx files (which i should have been using anyways), but I havent found a solution yet for using Response.Write in codebehind.  I think i'm going to decompile the .NET form class and override the actual rendering of these elements...which seems more efficient than substringing your entire HTML anyways.  I will post the solution if i can figure it out.

  • Anonymous
    August 28, 2008
    The comment has been removed

  • Anonymous
    September 01, 2008
    This was a great help.  I used Alex's approach, but made one small change.  Instead of overriding Render: protected override void Render(HtmlTextWriter writer) I defined a method called RenderFormValidationEarly protected void RenderFormValidationEarly(HtmlTextWriter writer) Which I call from the pages that testing has shown suffer from this problem.  I'm very happy with it!

  • Anonymous
    September 18, 2008
    The comment has been removed

  • Anonymous
    September 26, 2008
    I translated Alex's code to VB.NET for the great unwashed heathens who are not coding in C# :-) Imports Microsoft.VisualBasic Imports System.io Public Class BasePage    Inherits Page    Private Shared aspNetFormElements As String() _    = {"__EVENTTARGET", "__EVENTARGUMENT", "__VIEWSTATE", "__EVENTVALIDATION", "__VIEWSTATEENCRYPTED"}    Protected Overrides Sub Render(ByVal writer As HtmlTextWriter)        Dim sw As StringWriter = New StringWriter()        Dim htmlWriter As HtmlTextWriter = New HtmlTextWriter(sw)        MyBase.Render(htmlWriter)        Dim html As String = sw.ToString()        Dim formStart As Integer = html.IndexOf("<form")        Dim endForm As Integer = -1        If (formStart >= 0) Then            endForm = html.IndexOf(">", formStart)        End If        If (endForm >= 0) Then            Dim viewStateBuilder As StringBuilder = New StringBuilder()            For Each element As String In aspNetFormElements                Dim startPoint As Integer = html.IndexOf(String.Format("<input type='{0}' name='{1}'", "hidden", element))                If startPoint >= 0 AndAlso startPoint > endForm Then                    Dim endPoint As Integer = html.IndexOf("/>", startPoint)                    If (endPoint >= 0) Then                        endPoint += 2                        Dim viewStateInput As String = html.Substring(startPoint, endPoint - startPoint)                        html = html.Remove(startPoint, endPoint - startPoint)                        viewStateBuilder.Append(viewStateInput).Append("rn")                    End If                End If            Next            If (viewStateBuilder.Length > 0) Then                viewStateBuilder.Insert(0, "rn")                html = html.Insert(endForm + 1, viewStateBuilder.ToString())            End If        End If        writer.Write(html)    End Sub End Class

  • Anonymous
    September 26, 2008
    The comment has been removed

  • Anonymous
    September 26, 2008
    Another thing i noticed in the converted code from C# to VB, is the existence of "rn". which will produce the following hidden element replacement: rn<input type="hidden" name="__EVENTVALIDATION" the solution is to replace the following code: viewStateBuilder.Append(viewStateInput).Append("rn") TO viewStateBuilder.Append(viewStateInput).Append(vbCrLf) AND FROM viewStateBuilder.Insert(0, "rn") TO viewStateBuilder.Insert(0, vbCrLf)

  • Anonymous
    September 30, 2008
    Naji, good catches I sincerly apologize. It's just that I had loads of users bugging me about a fix and I was trying to get something out to them to shut them up. But haste always makes waste. I'm posting the revised code for those who need it. I changed all 'rn" sequences to Environment.Newline's since its not as platform specific and added double quotes on the attribute fields. Imports Microsoft.VisualBasic Imports System.io Public Class BasePage    Inherits Page    Private Shared aspNetFormElements As String() _    = {"__EVENTTARGET", "__EVENTARGUMENT", "__VIEWSTATE", "__EVENTVALIDATION", "__VIEWSTATEENCRYPTED"}       Protected Overrides Sub Render(ByVal writer As HtmlTextWriter)        Dim sw As StringWriter = New StringWriter()        Dim htmlWriter As HtmlTextWriter = New HtmlTextWriter(sw)        MyBase.Render(htmlWriter)        Dim html As String = sw.ToString()        Dim formStart As Integer = html.IndexOf("<form")        Dim endForm As Integer = -1        If (formStart >= 0) Then            endForm = html.IndexOf(">", formStart)        End If        If (endForm >= 0) Then            Dim viewStateBuilder As StringBuilder = New StringBuilder()            For Each element As String In aspNetFormElements                Dim startPoint As Integer = html.IndexOf(String.Format("<input type=""{0}"" name=""{1}""", "hidden", element))                If startPoint >= 0 AndAlso startPoint > endForm Then                    Dim endPoint As Integer = html.IndexOf("/>", startPoint)                    If (endPoint >= 0) Then                        endPoint += 2                        Dim viewStateInput As String = html.Substring(startPoint, endPoint - startPoint)                        html = html.Remove(startPoint, endPoint - startPoint)                        viewStateBuilder.Append(viewStateInput).Append(Environment.NewLine)                    End If                End If            Next            If (viewStateBuilder.Length > 0) Then                viewStateBuilder.Insert(0, Environment.NewLine)                html = html.Insert(endForm + 1, viewStateBuilder.ToString())            End If        End If        writer.Write(html)    End Sub End Class

  • Anonymous
    September 30, 2008
    Has everyone tried .NET 3.5 SP1 to see if that resolves the issue for them?  That should take care of this problem without the need for any code workarounds.

  • Anonymous
    September 30, 2008
    Tom from what I understand .NET 3.5 SP1 does solve this issue.  However, the economy is in the toilet at this point and my company isn't rushing to spend any money on technology upgrades. So unfortunately I'm stuck with .NET 2.0 for the time being. :-(

  • Anonymous
    September 30, 2008
    ton, .NET 3.5 SP1 is a free download that includes .NET 2.0 SP2.  I understand if it is about testing and that knid of stuff with having the new version.  But there isn't a cost from us for getting this.

  • Anonymous
    September 30, 2008
    The comment has been removed

  • Anonymous
    October 12, 2008
    Hi, I tried the VB versions of this code above. Unfortunately it didn’t quite work for me. I use master pages with a menu based on the.  Using this BasePage approach stops the Menu Friendly Adapter menu from working. Also, in the aspx mark up in the footer of my master page I have: <div> Copyright © 2006 - <%Response.Write(Year(Now()))%> </div> When using the BasePage the year now gets written at the top of the page instead of in the footer area. Any ideas on how to fix? Regards Smcoxon

  • Anonymous
    October 12, 2008
    I think I’ve resolved my issue… I removed the entire mark up in my master page footer <div> and used the master Page Init event to write the text and date in to the footer <div> innerHtml. This seems to work as the year string is no longer written to the top of the page using my original aspx mark up: <% Response.Write(Year(Now()) %>. The Friendly Menu Adapter is also working again by doing this. Regards Smcoxon PS. Any news on when a working 3.5 SP1 will be released?  There seems to be too many reported issues with the beta version to chance installing it.

  • Anonymous
    October 21, 2008
    Can anyone give me 'THE' accepted solution for this problem? My problem seems to be related to the fact that I have quite a large wizard control which has 1 user control embedded within each wizard step. One of the wizard steps has a user control with a gridView inside. The gridview also uses the DataKeys feature and I think this is causing the problem.

  • Anonymous
    November 03, 2008
    The comment has been removed

  • Anonymous
    November 30, 2008
       I found the current thread we are all reading on www.asp.net while I was searching for a problem with my membership and role providers.  I kept getting the following error: "Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that configuration specifies the same validationKey and validation algorithm. Auto Generate cannot be used in a cluster."    The problem was my login system worked fine on my local machine, but when I FTPed my application to my remote server and then launched it, the user names and roles I created locally would not authenticate.  Login would fail for these users.  If I then created new users with my application on my remote server they would authenticate properly.  In short, any time I moved my application to a new directory the users and roles created when the application resided in previous directories failed. I found a solution to the problem that worked for me.  The solution is to manually add the applicationName attribute to the <providers> node of your web.config file and give it a value, such as "/".  I wrote a short article about the process I used to fix the problem.  Hope it helps: http://www.itegritygroup.com/itegrity/seo-web-development-blog/index.php/2008/10/validation-viewstate-mac-failed/

  • Anonymous
    December 01, 2008
    Great article. this was exactly the problem i was having with my site <a href="http://www.wordbricks.com" /> ie when people try to add things to the basket before the page has finished loads completely. Thanks again.

  • Anonymous
    December 02, 2008
    Need to use fixed keys to encrypt/decrypt viewstate to avoid postback issues, whether its after long periods or after application pool is recycled.  I found this website for generating these keys for either macnine.config or web.config  http://www.orcsweb.com/articles/aspnetmachinekey.aspx

  • Anonymous
    December 06, 2008
    The comment has been removed

  • Anonymous
    December 07, 2008
    Baskar, How large of a viewstate are you using?  There isn't really a good size to tell you other then to check what your viewstates are.  You can try disabling viewstate if it is 2.0 and just use controlstate.

  • Anonymous
    December 22, 2008
    We had issues with __EVENTVALIDATION not being sent with long pages and users doing postbacks prior to page being fully rendered. Installing 2.0 SP2 via 3.5 SP1 seems to have solved it. Thanks for the heads up. Maybe the original article should be updated, though. The listed workarounds seem too much of a hassle now.

  • Anonymous
    December 23, 2008
    If you work with web sites in a complex/multi server environment you might be familiar with this error

  • Anonymous
    January 02, 2009
    In 2008 also i am not able to solve this issue.... can u suggest me another way to solve this ??? Plz mail me your suggestions at : hallowbestboy@gmail.com

  • Anonymous
    January 09, 2009
    The comment has been removed

  • Anonymous
    January 10, 2009
    The comment has been removed

  • Anonymous
    January 12, 2009
    Update: In my case I was NOT using gridview nor DataKeyNames nor slow loading page. Small page with on two buttons, two text boxex, and dropdownlist. Clicking the button1 (add) caused the above error every time. Problem turned out to be the form action property was pointing to  a non-existent page! I used a code-behind method when the Add button is clicked and do not use form.submit. When I cleared the action property of the form, problem went away. My "guess" is that the form submit happens before the code-behind code is processed, since even in debug I would get the error before the breakpoint was hit. Hope this leads to the final answer to this. thanks! Mike.

  • Anonymous
    February 12, 2009
    Hello, I had the same problem with the Web application installed in IIS 5.1 on Windows XP.  I don't know if the following text will solve your problem but it solved mine. The problem came out only after the machine was updated with the .NET framework 3.5. After reading this article 2 or 3 times and after I tried the solutions in the article (did not solve my problem), I discovered, in the problematic Web page, an old attribute in the tag "form".  I had the following in the tag: <form id="myForm" runat="server" method="post" action="myForm2.aspx" > I just removed the attribute "action" and everything works fine since. Hope it helps! Regards,

  • Anonymous
    February 17, 2009
    I am having this error on serveral sites. As usual it appears to be quite random and I've never been able to reproduce it consistently. It's not related to timing either as I have left pages sitting for five minutes, come back and hit a button and received this error. I get this error even though I have disabled viewstate validation! Someone at MS needs to pull their forearm out of their backside and do some proper research into this and get it fixed. I'm trying out option 3. I'm skeptical, but I'll see how it goes and report back if I stop seeing the error.

  • Anonymous
    February 17, 2009
    Option 3 didn't make any difference. However, something the client said about leaving the page open for a while and returning later to click on a link was triggering the error. So I have disabled session state (nvr use the thing) and I'll see if that works out.

  • Anonymous
    April 01, 2009
    I insatlled the .NET 3.5 SP1 (.NET 2.0 SP2) from the above source. Still the error persistes. I have no luck in resolving this error

  • Anonymous
    April 01, 2009
    Apps, Do you know what the situation is around when you get the error?  Can you repro it? Have any of the other workarounds helped?

  • Anonymous
    April 07, 2009
    How do I use Alex Class in a project?

  • Anonymous
    April 08, 2009
    Using a load testing tool, I can reproduce it by changing the Web Garden figure to > 1. The higher the wg figure the more Viewstate errors my load test will generate ( though the overall number is small, around 1% of completed tests ) 1 wg = 1 w3wp.exe process 2 wg = 2 w3wp.exe processes I'm guessing something gets mixed up with the wrong thread handling the another threads request, occasionally.

  • Anonymous
    April 23, 2009
    For those who need ASP.NET machine keys and French explanations, I wrote a simple generator you can find on my personal web site http://muniere.fr/Projects/KeysGenerator/ Hope it helps! Nico

  • Anonymous
    May 14, 2009
    I'm as well getting this error, mostly on the test server. It happens unpredictablely. My question is, can someone cause the error simply? Then it would be much easier to test these solutions. Basically, our app will timeout, and the login page, usually after sitting un-used for long periods of time will throw the error. Its occurred in localhost a handful of times. It would be nice to know if the error can be triggered easily, so I don't have to wait for app timeouts to fire, session timeouts to end. Maybe there is not a simple way, but just thought i would ask? thanks

  • Anonymous
    May 14, 2009
    I had this issue and found the cause to be the following.   I had a GridView with ButtonFields, and a Form.   The form action was set to post to page "X".  Later in my code, I caught the Selected Changed event of the GridView when the ButtonField was clicked or "Selected".  At that point I did a Server.Transfer to page X with the a data value in the row selected.  Basically when they selected a row in the grid i sent them to a details page of that row.  Turns out, I needed to remove the "action" from the form, and then it worked fine with no issues.  My environment is Windows Server 2003, .Net 2.0

  • Anonymous
    May 21, 2009
    The comment has been removed

  • Anonymous
    June 12, 2009
    In my case, this error was caused by hitting a site memory cap instituted by my web hosting company.  They increased my limit and it went away.

  • Anonymous
    June 20, 2009
    The comment has been removed

  • Anonymous
    June 20, 2009
    I should also mention the work I did was on W2k3 SP2 and IIS6.

  • Anonymous
    June 22, 2009
    Hi, I hit this error only if I implemented server side viewstate to my web app, and have callback. Any ideas? Thank you

  • Anonymous
    July 07, 2009
    Just wanted to comment.  We are using .NET 3.5 SP1 (which mean .NET 2.0 SP2) and we have a "fixed" MachineKey setting.  This issue is STILL happening.  So I will look at some of these resolutions and try to come up with something that works.

  • Anonymous
    July 17, 2009
    Excellent post!! 2 days spent looking for the reason for this untill I spotted that the __EventValidation is missing altogether!

  • Anonymous
    July 17, 2009
    FIX: Error message on an ASP.NET page after you submit a form that has the "action" attribute defined after you install the .NET Framework 2.0 SP2 or the .NET Framework 3.5 SP1: "Validation of viewstate MAC failed" @ http://support.microsoft.com/kb/970459

  • Anonymous
    July 19, 2009
    About WorkAround 3, the C# BasePage class, how do you inherit this page, when I put in behind Inherits in my .aspx file, I get an error saying it needs a different Model.

  • Anonymous
    July 27, 2009
    The comment has been removed

  • Anonymous
    July 28, 2009
    I tried Basepage third Solution but still it showing error , any idea to fix it?

  • Anonymous
    July 28, 2009
    Has anyone seen a different solution?  I've tried just about everything I can on this page and nothing works.

  • Anonymous
    August 03, 2009
    The comment has been removed

  • Anonymous
    August 26, 2009
    Actually, we're not using a farm server, we're not using anything that uses DataKeyNames (or anything that databinds for that matter), and the page is fairly small, but this error will come up after the webpage has been left open for quite some time, and the user attempts to make a postback. Anyone got some ideas?

  • Anonymous
    September 06, 2009
    Everything that was posted here did not solved the issue. In our DEV machine it was working fine. But in our PRD servers. it was not working same issues that you reported. Has this something to do with Firewalls? Maybe we're fixing here that was not the main issue at all? any ideas? updates?

  • Anonymous
    September 07, 2009
    One thing you can do is use one of the available ViewState Decoders to look at the ViewState and see what it looks like.  The main thing to look for is if it is getting cut off.  You can find a couple of decoders on Scott's blog at: http://weblogs.asp.net/scottgu/archive/2003/02/16/2495.aspx

  • Anonymous
    September 15, 2009
    Re: Ron's comment - I have exactly the same issue - if the page is left open for some time, then I click a link to open a popup and perform a callback to rebind some data, I'll get the viewstate error everytime.  Seems to be linked to the session timeout.  Out of options now!

  • Anonymous
    September 15, 2009
    Unfortunately, the issue still occurred for me. I installed the latest SP and when I run the app through VS2008 and perform the clicking, the error still persist.

  • Anonymous
    November 08, 2009
    i am inheriting my page from BasePage but still i am getting this error then what may be the cause for it ? plz mail me at aruninnice@gmail.com

  • Anonymous
    January 27, 2010
    We had removed the action tag and it worked for us.

  • Anonymous
    January 31, 2010
    I have the same situation as Ron and Tony has. If I left a page open for a while and than post back, the page redirects with Response.Redirect to login page. Than I try to login and on the first post back on the login page I get the error.

  • Anonymous
    February 03, 2010
    hello, I was working on VS2005 Team Suite with 2.0 framework. I update my Win XP with SP3 and Other Updates. Now i have 2.0SP2,3.0SP2,3.5SP1. I didnt upgrade my project from 2.0. Afret that i start facing the above prob(<machine.....>). I add machine tag under  <system.web> tag and problem solves, I am confused why this error occures. I shoot a mail to MS Support team too. If anyone has answer pls answer. Regards. SPandey

  • Anonymous
    March 21, 2010
    You asked if this is still happening even after SP1, and yes it is. I have a site with a master page and a form page, my form is nothing but a simple user registration, I have no grids or large controls. My Viewstate is tiny as I am dealing with 10 textboxes and 12 checkboxes. this is supposed to be a 1 hour job creating a page that grabs this little data and sending it to a DB. I am running vista, vs 2008 sp1 and IE 8 I am bothered by the amount of workarounds here and no solutions to the actual problem. I guess I will go and trial and error my way through the workarounds.

  • Anonymous
    April 01, 2010
    The comment has been removed

  • Anonymous
    April 13, 2010
    Hey everyone, I am looking for someone that has this problem that is willing to work with Microsoft to try to get it resolved.  I am interested in someone that has the 3.5 SP1 (.NET 2.0 SP2) installed and is still seeing the problem.  We want someone that has this reproduced that we can work with to fix it better.  If you are willing to help, please send me an email from http://blogs.msdn.com/tom/contact.aspx Thanks

  • Anonymous
    April 13, 2010
    Hi Tom, I'm still seeing the problem though I tried to implement Alex's code. My problem is only appearing when I use other browser than IE. The scenario is, after user logout from the session, it will be redirect to other website. Then user click back button from browser and try to login again (Submit) from the login page, the message of "Validation of viewstate MAC failed error" appear. I'm using master page and .NET 2.0 SP2. But if we force the browser to reload, the message is gone. It is only happen to Chrome, Firefox, and Safari. It's just nice in IE. I've tried to use workaround option 1 and also your code, but was not successful. It's just weird since the error only being shown for other browser.

  • Anonymous
    May 09, 2010
    The comment has been removed

  • Anonymous
    July 07, 2010
    my application is using framework 4.0 and still has the problem.  

  • Anonymous
    July 15, 2010
    The comment has been removed

  • Anonymous
    July 27, 2010
    yunus, Have you tried setting the machineKey to be the same on all servers?

  • Anonymous
    November 21, 2010
    For me only adding the machineKey -Element (created by the machineKey generator) into the Web.Config file solved the issue. Thanks for the contribution to all!

  • Anonymous
    November 27, 2010
    Tom, do you understand WHY the machineKey should be the same on all servers in a web farm or cluster? The reason is that the viewstate is encrypted using the machine key. Once you inderstand that, then you would als understand why a machine key should be added when you only have 1 server instead of using your "workaround". Becaue when you don't  use a machineKey, ASP.NET will generate one for you. Which i no problem untill the ASP.NET worker process recycles. When this happens between 2 postbacks, the viewstate which has been encrypted using the first generated machine key cannot be decrypted anymore using the newly generated machine key, resulting in thi error. So adding a machineKey will solve thi error withhout uing your workarounds.....

  • Anonymous
    December 03, 2010
    Had the same issue. After much digging, found it was caused by the form having a different action to the current URL due to URL Rewriting. The page in question has a DataList with a control to advance to the next page. On the first page everything is fine. On any other DataList page I get the Validation error if I press any anything that causes a postback event. The displaying of pages for the DataList is controlled by a QueryString  parameter. The fix was simply to overwrite the form action in the page prerender function so that it matches the URL on display in the address bar. Actual URL: /site/ShowCategory.aspx?categoryid=106&page=2 User sees (through URL rewriting): /site/c106/the category description/p-2 Without overwriting the form action, the system was setting the action to: /site/p-2?category=106&page=2

  • it was this that was causing the issue. On inspection it looks like the system was taking the user readable URL and determining the page to be p-2, then taking the querystring after the transformation and adding it to the back end of the URL - creating total garbage. Hope this helps others that may have a similar issue.
  • Anonymous
    January 13, 2011
    I had this problem too. The reason is that webpages in one browser(IE 7) are always out of date(due to the browser settings). I think it will be solved by adding a machinekey, so that the viewstate value will not be changed. I'm using .net 2.0, workaround 1 didn't solve the problem. And there was an javascript error when I used workaround 3 in IE 6. Thanks for all the posts, I learned more on the possible causes of this exception.

  • Anonymous
    March 07, 2011
    Tried BasePage class, .NET 3.5 SP1 and still get Viewstate MAC errors.

  • Anonymous
    April 17, 2011
    The comment has been removed

  • Anonymous
    July 05, 2011
    In my website i did a mail-send form based on ASP.NET with MailMessege. At the beginning it worked fine but now that problem occurs. Can you help me please? The website is in hebrew: www.habaithakatom.co.il

  • Anonymous
    July 10, 2011
    I was getting the same error without a webfarm, but only after a form with a gridview was left open and unused for some time. In this case it turned out to be occurring as the session had expired (set by default to 20 mins). I had two applications with this issue, one was solved as I had to use forms authentication and you just login again after session expires. The other was sorted by increasing the session timeout in the web.config.

  • Anonymous
    August 02, 2011
    The ViewBasket.aspx and ViewBasket.aspx.vb code-behind are incorrectly referencing the orderConfirmation page/class. Replace any instances of orderConfirmation with ViewBasket and it works as it should.

  • Anonymous
    October 25, 2011
    I am seeing this error on an asp.net 2.0 formview with about 50 controls (radio buttons, checkboxes, textboxes). The page does a lot of validation, to make sure that for example exactly 3 out of 11 checkboxes are checked.  I am not an expert coder and am not sure I understand the suggested workarounds about overriding the Render method or disabling the form and then re-enabling it.  I am also not sure I understand what this has to do with the viewstate failing to load before the page is submitted -- since the controls do not have default values set, it takes the human user some time (probably 5-10 minutes) to go through the form, clicking on things, so how can it not have completely loaded yet? My question is: since I am not using the formview's built-in Update functionality -- the update button has no Commandname property but instead its Onclick calls a subroutine that sets all the SQLDatasource's update parameters and then calls update() -- do I even need the formview's DataKeyNames attribute?  It seems to work without it.  And if I omit DataKeyNames can I avoid this error?  In our case it is an intermittent error anyway.   At this point, the alternative I am facing is to take some time to break up the form into 4 or 5 pages, which might be a good idea anyway -- I'm not sure which is more annoying to the user, filling out a very long form or filling out 4 or 5 shorter ones. Thanks.

  • Anonymous
    November 23, 2011
    I converted this code to VB (not that I wanted to, but the website I'm maintaining is written in VB):    Protected Overrides Sub Render(writer As System.Web.UI.HtmlTextWriter)        Dim stringWriter As StringWriter = New StringWriter()        Dim htmlWriter As HtmlTextWriter = New HtmlTextWriter(stringWriter)        MyBase.Render(htmlWriter)        Dim html As String = stringWriter.ToString()        Dim aspnet_formelems(4) As String        aspnet_formelems(0) = "__EVENTTARGET"        aspnet_formelems(1) = "__EVENTARGUMENT"        aspnet_formelems(2) = "__VIEWSTATE"        aspnet_formelems(3) = "__EVENTVALIDATION"        aspnet_formelems(4) = "__VIEWSTATEENCRYPTED"        For Each elem As String In aspnet_formelems            'Response.Write("input type=""hidden"" name=""" & abc.ToString & """")            Dim StartPoint As Integer = html.IndexOf("<input type=""hidden"" name=""" + elem.ToString() + """")            If StartPoint >= 0 Then                'does __VIEWSTATE exist?                Dim EndPoint As Integer = html.IndexOf("/>", StartPoint) + 2                Dim ViewStateInput As String = html.Substring(StartPoint, EndPoint - StartPoint)                html = html.Remove(StartPoint, EndPoint - StartPoint)                Dim FormStart As Integer = html.IndexOf("<form")                Dim EndForm As Integer = html.IndexOf(">", FormStart) + 1                If EndForm >= 0 Then                    html = html.Insert(EndForm, ViewStateInput)                End If            End If        Next        writer.Write(html)    End Sub

  • Anonymous
    January 13, 2012
    I was facing the same problem but in my case the problem was that I have the wrong action name in the form tag which was causing the problem.  <form action="improvethought.aspx" method="post" id="addForm" runat="server">. correcting the action name solved my problem. Thanks  

  • Anonymous
    May 03, 2012
    ran into this same issue with APP running on .NET 4.0. Two different environments using load balancing. On one resetting the sticky sessions from 3 to 30 minutes resolved the issue and on the other turning off JsessionID in the balancer resolved the issue.

  • Anonymous
    January 28, 2013
    Thanks for detailed information about cause and solution to fix it.

  • Anonymous
    April 29, 2013
    The comment has been removed

  • Anonymous
    June 22, 2013
    I tried adding a machine key and inheriting from BasePage and got the same error. My workaround is to use Response.Redirect().

  • Anonymous
    June 27, 2013
    The comment has been removed

  • Anonymous
    August 04, 2013
    I think the 3rd solution, by Alex, solve my problem. Thanks.

  • Anonymous
    September 23, 2013
    ARR 3.0: Client Affinity Not Working Even though I have set the Client Affinity in my server farm, the requests from same client are sent to different servers.  This behavior I have confirmed in Monitoring and Management section in the server farm. Also I am getting following error in the client, Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that <machineKey> configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster. Any solution ?

  • Anonymous
    October 28, 2013
    Yeah...so none of these suggestions work if you're using SharePoint with MasterPages enabled. Try creating a custom upload form that is required to both allow the user to upload a file and save data entered by the user via custom field types on the same form and see what happens. Wait for it... Wait for it... Boom!