I have a view with a model that has several fields. When I render the view on the GET I have a hidden field storing a code which is empty at this point. Then I POST and on the action I add a value to this code field through the model and send the model to the view like:
return View (model);
When the view renders, the hidden field does not have the code value but the view does contain all other values entered in the first step. So now when I post on a second button the model passed to the action does not contain the hidden code value I passed to it on the first post response.
If I updated the model on the first post sent it back to the view with new values, should I not get that code stored in a hidden input in the view available and being able to post it back again to the action?
I just also realized that if I change any model field on the first post back and send the updated model to the view it will only retain values from the first POST action. Do I have a cache issue here?, how do i manage this behavior? thanks
You should remove it from ModelState before changing the value in your POST action:
The reason you need to do this is because Html helpers such as
Html.HtextBoxFor,Html.HiddenFor, … first use the value from modelstate when binding and then the value from your model. If you don’t remove the value from ModelState then theHiddenForhelper will use the original POSTed value which is an empty string and not the value you modified in your action.