In web application development we often need to use the hidden fields inside the form, the field may contains any data like primary key of table, username etc. Any data that we don’t want people see. So what will happened if your Hidden field not getting updated ?
You whole module work flow may affected due to this problem. This problem does not occur each time its very rare case when you find your values in Hidden field not getting updated .
What was happening in my case I’ve had near around 32 partial views (and each partial view had hidden field with same Id) I was using div and according to the request I was calling json to get html of partial and putting inside div. everything was working fine, I don’t had any issue about hidden field everything was working fine but the moment I added 33th partial view not sure what happened, hidden field was not getting updated in case when html of newly added partial view requested.
Things I considered to change
As you know I was directly overriding the new html with old, so I thought jquery DOM may be confuse because all partial view was sharing hidden field with same id, so instead overriding the html I did remove the existing html of partial view and then I put html of requested partial view. I was very disappointed that this trick was also not working.
I got clue
Well, this was very annoying why value in Hidden field not getting updated even I am now removing old and placing new html, still issue was there. Suddenly, one thing popup in my mind to check what being returned from server and when I checked I was shocked to see this was not related to jquery DOM because server was returning the hidden field with old value, I was speechless and I was upset that now how I can fix this since this is not something that I can change because I was using pre defined methods of c# in MVC.
Solution! Hidden field not getting updated
I dig around to find out the root of the issue and one of the msdn article says that the pre defined Html helpers does not fetch data from model that we pass instead they read data from model state, so the solution was, I had to call the the method ModelState.Clear() on submit action method, this then removes the all saved data from model state and when we will d0 html request via json then system will check in model state in this case model state will be empty now system will read fresh data and return.
So the solution is if your Hidden field not getting updated then call the ModelState.Clear() method on action result that uses(HttpPost attribue) and it will remove all data from model state and so on next request system have to return the fresh output!.
Hope this article will help you.