ASP.NET MVC – Validation of viewstate MAC failed error!

If you are just kick starting with ASP.NET MVC like me, you might have stumbled across this error :). This might have caused may be due to

  • more than one form tag
  • postback on a page containing a ViewUserControl

There are several other reasons for this error to pop up, but in ASP.NET MVC these 2 are the major ones. I was using RenderPartial to render one of my MVC usercontrols in one of my views on which when I did a postback I got this error.

I do not want to belabor too much on this topic since there are lots of discussions on this bug in ASP.NET, here are some,

In fact, this issue needs to be resolved within the ASP.NET MVC source code. Although, since we need not do that, I found a HttpModule which can be used to get rid of this error nicely.

Here is the link for the same, This HttpModule certainly resolved my issue, for the time being!

I realized that adding this module did some funny stuff with the external files I had in my project, like CSS and JavaScript. Somehow these files were not added to my pages while the page was rendered.

So, the final solution, I used an extended class of ViewUserControl. Here is a link by Mauricio which explains this in detail. Basically, in the ASP.NET MVC source code, the ViewUserControl is actually rendered within a fake view page, due to which our settings in web.config do not apply to usercontrols. Finally everything works now, phew!

Happy Programming!