Hey I would love to know what you think while reading my posts. Please comment!.

Using MaxHttpCollectionKeys to fix error 'Operation is not valid due to the current state of the object' during postback

I came across this error recently, on a website which I had built for one of our clients.

`Operation is not valid due to the current state of the object`.

This occurs on Postback of the page.

After a quick search, I found the answer on Stackoverflow

A security update for Microsoft .Net Framework meant that the number of fields which, by default, were allowed to be posted to a page was set to 1000, however the website in question was posting more. A quick fix for this is to add a setting into your web.config file;

<add key="aspnet:MaxHttpCollectionKeys" value="2001" />

However, this forced me to realise how poorly coded this individual page was, and that I had been using far too many HiddenFields within DataGrids, GridViews and Repeaters.

On this problematic page, I was using HiddenFields to hold information for each item in the repeater control, and when the repeater was being Paged this worked fine. The client had asked for a facility to "View All", which meant that there were potentially 500 + items within the repeater, and each Item had 5 HiddenFields. I had never really thought about it before, but now I realise that there would be times when the page was posting 2500+ fields to the page!!! No No No.

I have updated the HiddenFields to Literals now and everything is working as it should, also I have cut the ViewState down massively!

This is just another reason though why I am glad to be moving away from webforms and the <form runat="server"> wrapping pages. MVC FTW!!! :)

PLEASE LEAVE COMMENTS! I am always interested in hearing back from those who read my blog. Please leave a comment if you found this useful, want to suggest any changes to my code, or anything else! Thanks!

About Me

Tim James I'm Tim, a web applications developer from Glasgow, Scotland. Currently working for Kingfisher Systems Ltd, building bespoke systems within the Car Auction industry.

  • C#
  • VB.NET
  • .NET MVC
  • Web API
  • Razor
  • HTML5
  • CSS3
  • jQuery
  • WCF
  • SQL
  • knockout.js
  • Angularjs
  • AJAX
  • APIs
  • SignalR
Why not follow me on twitter? Follow me on Twitter