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,

http://stackoverflow.com/questions/230014/postback-not-working-with-asp-net-routing-validation-of-viewstate-mac-failed

http://stackoverflow.com/questions/121579/im-getting-a-strange-unhandled-exception-from-my-asp-net-application-validatio

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, http://mvcfriendlymodule.codeplex.com/. 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 http://bugsquash.blogspot.com/2009/02/aspnet-mvc-postback-support.html 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!