I have an issue when using a hidden field in an MVC Form Post. When the hidden field is generated via a HTML Helper it won\'t preserve it\'s value during the postback. But w
Although not obvious and I found it difficult to find many articles on this subject to clarify it for me in the past the default behaviour in ASP.NET MVC is the following:
If you are using HTML Helpers and you are rendering the same View in response to a POST
it is assumed that you are responding to failed form validation.
Therefore the values before being set in the POST
will always be rendered back in the view from ModelState.
You have a few options:
ModelState.Clear();
in your post. Not recommended as the framework has not been designed this way.Post-Redirect-Get
pattern and only display validation failure, as the framework was designed (as @StephenMuecke mentions).Request.Form
values instead and remove the SomeViewModel someViewModel
parameter. Wouldn't recommend this as you lose all benefits of model binding.ModelState.Remove
for the specific field, again not recommended.The best article I found on this was article from Simon Ince in 2010:
ASP.NET MVC’s Html Helpers Render the Wrong Value!
Another one by Rick Strahl:
ASP.NET MVC Postbacks and HtmlHelper Controls ignoring Model Changes