I was idly coding an ASP.NET MVC application – it worked fine, I was actually starting to understand how MVC works. Then I added a GridView to a view. And suddenly, BOOM, an error when debugging:
[HttpException (0x80004005): 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.]
I was not on a Web Farm – and this error was completely new to me. So I hit the Internets… and got a load of answers. Most were related to GridView, indeed – namely, if a large page with GridView loads slowly, viewstate may not be completely loaded when user re-submits the form (see Validation of viewstate MAC failed error) and so forth.
But my page was tiny. Two edit fields, a drop-down and an empty GridView, that’s it. Not to mention, the issue was supposedly fixed in .NET 3.5 SP1, which I was using.
I tried various recommended solutions. I generated <machineKey> using <machineKey> Generator, I removed the GridView, I disabled event validation (<system.web> <pages enableViewStateMac="false" /> </system.web>), rebooted just in case… but no use.
I was getting desperate. But then I saw a comment to some forum post – make sure you don’t have two forms in one page. I knew I didn’t have two forms, but I checked my view anyway – and… for my surprise, there were two forms – HTML <form>..</form> tags around <% using (Html.BeginForm()) { } . How did that happen? I removed <form></form> – and everything worked fine.
I figured out what had happened – when I dragged’n'dropped GridView to a view, Visual Studio designer didn’t “see” a form on the page. So it added form around all the form controls it could find – in effect creating a form inside a form. I tried to add GridView again – and indeed, it added form tags again.
So, if you get this error, make sure you don’t have extra form tags on your page.