Hidden field not posting back in ASP .Net MVC

Recently I come across this issue where I had a property in my model class and I was passing its value to a hidden field on html form on the view. I was able to set its value from user action on another input field but when I tried to post it back to controller I was not able to receive its value even though I could see the value from browser console window. It also happened to me a few days ago but at the time I found a workaround by passing the same value to another property but when it happened again I set out to find the real reason.

As usual I started by searching on Google and found a few threads on Stackoverflow related this topic. In one thread it was suggested I should check Model State and make it clear with ModelState.Clear() but it impacted other parts of code and didn’t solved the original issue. Another thread suggested to use html hidden input fields directly without the help of Html.HiddenFor helper. I tried that but still it was not fruitful.

Just as I was about to give up I went to my model class again a found the culprit. The property for which I was setting the hidden field looked something like this.

public int TotalCount { get; internal set; }

Can you figure out whats wrong with this property?  Look at its getter setter. Specifically its setter is set to be internal. This was the reason its value was not getting set from the post action. So I removed the internal keyword and voila my problem was solved. So if you are not able to receive the value of any of your model class property in the post action, look out for this keyword.

Leave a Reply